]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
3625c4829abc92167771d4d3f78554ea00856c6e
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * $Id: ad_open.c,v 1.20 2002-10-10 20:27:36 jmarcus Exp $
3  *
4  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu)
5  * Copyright (c) 1990,1991 Regents of The University of Michigan.
6  * All Rights Reserved.
7  *
8  * Permission to use, copy, modify, and distribute this software and
9  * its documentation for any purpose and without fee is hereby granted,
10  * provided that the above copyright notice appears in all copies and
11  * that both that copyright notice and this permission notice appear
12  * in supporting documentation, and that the name of The University
13  * of Michigan not be used in advertising or publicity pertaining to
14  * distribution of the software without specific, written prior
15  * permission. This software is supplied as is without expressed or
16  * implied warranties of any kind.
17  *
18  *      Research Systems Unix Group
19  *      The University of Michigan
20  *      c/o Mike Clark
21  *      535 W. William Street
22  *      Ann Arbor, Michigan
23  *      +1-313-763-0525
24  *      netatalk@itd.umich.edu
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif /* HAVE_CONFIG_H */
30
31 #include <string.h>
32 #ifdef HAVE_FCNTL_H
33 #include <fcntl.h>
34 #endif /* HAVE_FCNTL_H */
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif /* HAVE_UNISTD_H */
38 #include <errno.h>
39 #include <atalk/logger.h>
40
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/param.h>
45 #include <sys/mman.h>
46
47 #include <netatalk/endian.h>
48 #include <atalk/adouble.h>
49
50 #include "ad_private.h"
51
52 #ifndef MAX
53 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
54 #endif /* ! MAX */
55
56 /*
57  * AppleDouble entry default offsets.
58  * The layout looks like this:
59  *
60  * this is the v1 layout:
61  *        255     200             16      32              N
62  *      |  NAME |    COMMENT    | FILEI |    FINDERI    | RFORK |
63  *
64  * we need to change it to look like this:
65  *
66  * v2 layout:
67  * field       length (in bytes)
68  * NAME        255
69  * COMMENT     200
70  * FILEDATESI  16     replaces FILEI
71  * FINDERI     32  
72  * DID          4     new
73  * AFPFILEI     4     new
74  * SHORTNAME   12     8.3 new
75  * RFORK        N
76  * 
77  * so, all we need to do is replace FILEI with FILEDATESI, move RFORK,
78  * and add in the new fields.
79  *
80  * NOTE: the HFS module will need similar modifications to interact with
81  * afpd correctly.
82  */
83  
84 #define ADEDOFF_MAGIC        (0)
85 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
86 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
87 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
88
89 /* initial lengths of some of the fields */
90 #define ADEDLEN_INIT     0
91
92 /* make sure we don't redefine ADEDOFF_FILEI */
93 #ifdef ADEDOFF_FILEI
94 #undef ADEDOFF_FILEI
95 #endif /* ADEDOFF_FILEI */
96
97 #define ADEID_NUM_V1         5
98 #define ADEDOFF_NAME_V1      (AD_HEADER_LEN + ADEID_NUM_V1*AD_ENTRY_LEN)
99 #define ADEDOFF_COMMENT_V1   (ADEDOFF_NAME_V1 + ADEDLEN_NAME)
100 #define ADEDOFF_FILEI        (ADEDOFF_COMMENT_V1 + ADEDLEN_COMMENT)
101 #define ADEDOFF_FINDERI_V1   (ADEDOFF_FILEI + ADEDLEN_FILEI)
102 #define ADEDOFF_RFORK_V1     (ADEDOFF_FINDERI_V1 + ADEDLEN_FINDERI)
103
104 /* i stick things in a slightly different order than their eid order in 
105  * case i ever want to separate RootInfo behaviour from the rest of the 
106  * stuff. */
107 #define ADEID_NUM_V2         9
108 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
109 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
110 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
111 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
112 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
113 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
114 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
115 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
116 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
117
118
119
120 /* we keep local copies of a bunch of stuff so that we can initialize things 
121  * correctly. */
122
123 /* Bits in the finderinfo data. 
124  * see etc/afpd/{directory.c,file.c} for the finderinfo structure
125  * layout. */
126 #define FINDERINFO_CUSTOMICON 0x4
127 #define FINDERINFO_CLOSEDVIEW 0x100
128
129 /* offsets in finderinfo */
130 #define FINDERINFO_FRTYPEOFF   0
131 #define FINDERINFO_FRCREATOFF  4
132 #define FINDERINFO_FRFLAGOFF   8
133 #define FINDERINFO_FRVIEWOFF  14
134
135 /* invisible bit for dot files */
136 #define ATTRBIT_INVISIBLE     (1 << 0)
137 #define FINDERINFO_INVISIBLE  (1 << 14)
138
139 /* this is to prevent changing timezones from causing problems with
140    localtime volumes. the screw-up is 30 years. we use a delta of 5
141    years.  */
142 #define TIMEWARP_DELTA 157680000
143
144
145 struct entry {
146   u_int32_t id, offset, len;
147 };
148
149 #if AD_VERSION == AD_VERSION1 
150 static const struct entry entry_order[] = {
151   {ADEID_NAME, ADEDOFF_NAME_V1, ADEDLEN_INIT},
152   {ADEID_COMMENT, ADEDOFF_COMMENT_V1, ADEDLEN_INIT},
153   {ADEID_FILEI, ADEDOFF_FILEI, ADEDLEN_FILEI},
154   {ADEID_FINDERI, ADEDOFF_FINDERI_V1, ADEDLEN_FINDERI},
155   {ADEID_RFORK, ADEDOFF_RFORK_V1, ADEDLEN_INIT},
156   {0, 0, 0}
157 };
158 #else /* AD_VERSION == AD_VERSION2 */
159 static const struct entry entry_order[] = {
160   {ADEID_NAME, ADEDOFF_NAME_V2, ADEDLEN_INIT},
161   {ADEID_COMMENT, ADEDOFF_COMMENT_V2, ADEDLEN_INIT},
162   {ADEID_FILEDATESI, ADEDOFF_FILEDATESI, ADEDLEN_FILEDATESI},
163   {ADEID_FINDERI, ADEDOFF_FINDERI_V2, ADEDLEN_FINDERI},
164   {ADEID_DID, ADEDOFF_DID, ADEDLEN_DID},
165   {ADEID_AFPFILEI, ADEDOFF_AFPFILEI, ADEDLEN_AFPFILEI},
166   {ADEID_SHORTNAME, ADEDOFF_SHORTNAME, ADEDLEN_INIT},
167   {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
168   {ADEID_RFORK, ADEDOFF_RFORK_V2, ADEDLEN_INIT},
169   {0, 0, 0}
170 };
171 #endif /* AD_VERSION == AD_VERSION2 */
172
173 #if AD_VERSION == AD_VERSION2
174
175
176 static __inline__ int ad_v1tov2(struct adouble *ad, const char *path)
177 {
178   struct stat st;
179   u_int16_t attr;
180   char *buf;
181   int fd, off;
182   
183   /* check to see if we should convert this header. */
184   if (!path || (ad->ad_version != AD_VERSION1))
185     return 0;
186
187   /* convert from v1 to v2. what does this mean?
188    *  1) change FILEI into FILEDATESI
189    *  2) create space for SHORTNAME, AFPFILEI, DID, and PRODOSI
190    *  3) move FILEI attributes into AFPFILEI
191    *  4) initialize ACCESS field of FILEDATESI.
192    *
193    *  so, we need 4*12 (entry ids) + 12 (shortname) + 4 (afpfilei) +
194    *  4 (did) + 8 (prodosi) = 76 more bytes.  */
195   
196 #define SHIFTDATA (AD_DATASZ2 - AD_DATASZ1)
197
198   /* bail if we can't get a lock */
199   if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0) < 0) 
200     goto bail_err;
201   
202   if ((fd = open(path, O_RDWR)) < 0) 
203     goto bail_lock;
204   
205   if (fstat(fd, &st) ||
206       ftruncate(fd, st.st_size + SHIFTDATA) < 0) {
207     goto bail_open;
208   }
209   
210   /* last place for failure. */
211   if ((void *) (buf = (char *) 
212                 mmap(NULL, st.st_size + SHIFTDATA,
213                      PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == 
214           MAP_FAILED) {
215     goto bail_truncate;
216   }
217   
218   off = ad->ad_eid[ADEID_RFORK].ade_off;
219
220 #ifdef USE_MMAPPED_HEADERS
221   /* okay, unmap our old ad header and point it to our local copy */
222   munmap(ad->ad_data, off);
223   ad->ad_data = buf;
224 #endif /* USER_MMAPPED_HEADERS */
225
226   /* move the RFORK. this assumes that the RFORK is at the end */
227   memmove(buf + off + SHIFTDATA, buf + off, 
228           ad->ad_eid[ADEID_RFORK].ade_len);
229   
230   /* now, fix up our copy of the header */
231   memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
232   
233   /* replace FILEI with FILEDATESI */
234   ad_getattr(ad, &attr);
235   ad->ad_eid[ADEID_FILEDATESI].ade_off = ADEDOFF_FILEDATESI;
236   ad->ad_eid[ADEID_FILEDATESI].ade_len = ADEDLEN_FILEDATESI;
237   ad->ad_eid[ADEID_FILEI].ade_off = 0;
238   ad->ad_eid[ADEID_FILEI].ade_len = 0;
239   
240   /* add in the new entries */
241   ad->ad_eid[ADEID_DID].ade_off = ADEDOFF_DID;
242   ad->ad_eid[ADEID_DID].ade_len = ADEDLEN_DID;
243   ad->ad_eid[ADEID_AFPFILEI].ade_off = ADEDOFF_AFPFILEI;
244   ad->ad_eid[ADEID_AFPFILEI].ade_len = ADEDLEN_AFPFILEI;
245   ad->ad_eid[ADEID_SHORTNAME].ade_off = ADEDOFF_SHORTNAME;
246   ad->ad_eid[ADEID_SHORTNAME].ade_len = ADEDLEN_INIT;
247   ad->ad_eid[ADEID_PRODOSFILEI].ade_off = ADEDOFF_PRODOSFILEI;
248   ad->ad_eid[ADEID_PRODOSFILEI].ade_len = ADEDLEN_PRODOSFILEI;
249   
250   /* shift the old entries (NAME, COMMENT, FINDERI, RFORK) */
251   ad->ad_eid[ADEID_NAME].ade_off = ADEDOFF_NAME_V2;
252   ad->ad_eid[ADEID_COMMENT].ade_off = ADEDOFF_COMMENT_V2;
253   ad->ad_eid[ADEID_FINDERI].ade_off = ADEDOFF_FINDERI_V2;
254   ad->ad_eid[ADEID_RFORK].ade_off = ADEDOFF_RFORK_V2;
255   
256   /* switch to v2 */
257   ad->ad_version = AD_VERSION2;
258   
259   /* move our data buffer to make space for the new entries. */
260   memmove(buf + ADEDOFF_NAME_V2, buf + ADEDOFF_NAME_V1,
261           ADEDOFF_RFORK_V1 - ADEDOFF_NAME_V1);
262   
263   /* now, fill in the space with appropriate stuff. we're
264      operating as a v2 file now. */
265   ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
266   memset(ad_entry(ad, ADEID_DID), 0, ADEDLEN_DID);
267   memset(ad_entry(ad, ADEID_AFPFILEI), 0, ADEDLEN_AFPFILEI);
268   ad_setattr(ad, attr);
269   memset(ad_entry(ad, ADEID_SHORTNAME), 0, ADEDLEN_SHORTNAME);
270   memset(ad_entry(ad, ADEID_PRODOSFILEI), 0, ADEDLEN_PRODOSFILEI);
271   
272   /* rebuild the header and cleanup */
273   ad_rebuild_header(ad);
274   munmap(buf, st.st_size + SHIFTDATA);
275   close(fd);
276   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0);
277
278 #ifdef USE_MMAPPED_HEADERS
279   /* now remap our header */
280   ad->ad_data = mmap(NULL, ADEDOFF_RFORK_V2, PROT_READ | PROT_WRITE,
281                      (ad_getoflags(ad, ADFLAGS_HF) & O_RDWR) ? MAP_SHARED :
282                      MAP_PRIVATE, ad->ad_hf.adf_fd, 0);
283   if (ad->ad_data == MAP_FAILED)
284     goto bail_err;
285 #endif /* USE_MMAPPED_HEADERS */
286
287   return 0;
288   
289 bail_truncate:
290   ftruncate(fd, st.st_size);
291 bail_open:
292   close(fd);
293 bail_lock:
294   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0);
295 bail_err:
296   return -1;
297 }
298 #endif /* AD_VERSION == AD_VERSION2 */
299
300
301 /* read in the entries */
302 static __inline__ void parse_entries(struct adouble *ad, char *buf,
303                                     u_int16_t nentries)
304 {
305     u_int32_t           eid, len, off;
306
307     /* now, read in the entry bits */
308     for (; nentries > 0; nentries-- ) {
309         memcpy(&eid, buf, sizeof( eid ));
310         eid = ntohl( eid );
311         buf += sizeof( eid );
312         memcpy(&off, buf, sizeof( off ));
313         off = ntohl( off );
314         buf += sizeof( off );
315         memcpy(&len, buf, sizeof( len ));
316         len = ntohl( len );
317         buf += sizeof( len );
318
319         if ( 0 < eid && eid < ADEID_MAX ) {
320             ad->ad_eid[ eid ].ade_off = off;
321             ad->ad_eid[ eid ].ade_len = len;
322         } else {
323             LOG(log_debug, logtype_default, "ad_refresh: nentries %hd  eid %d\n",
324                     nentries, eid );
325         }
326     }
327 }
328
329
330 /* this reads enough of the header so that we can figure out all of
331  * the entry lengths and offsets. once that's done, we just read/mmap
332  * the rest of the header in.
333  *
334  * NOTE: we're assuming that the resource fork is kept at the end of
335  *       the file. also, mmapping won't work for the hfs fs until it
336  *       understands how to mmap header files. */
337 static __inline__ int ad_header_read(struct adouble *ad)
338 {
339 #ifdef USE_MMAPPED_HEADERS
340     char                buf[AD_ENTRY_LEN*ADEID_MAX];
341 #else /* USE_MMAPPED_HEADERS */
342     char                *buf = ad->ad_data;
343 #endif /* USE_MMAPPED_HEADERS */
344     u_int16_t           nentries;
345     int                 len;
346     static int          warning = 0;
347
348     /* read the header */
349     if ( ad->ad_hf.adf_off != 0 ) {
350       if ( lseek( ad->ad_hf.adf_fd, 0L, SEEK_SET ) < 0L ) {
351                 return( -1 );
352       }
353       ad->ad_hf.adf_off = 0;
354     }
355
356     if (read( ad->ad_hf.adf_fd, buf, AD_HEADER_LEN) != AD_HEADER_LEN) {
357         if ( errno == 0 ) {
358             errno = EIO;
359         }
360         return( -1 );
361     }
362     ad->ad_hf.adf_off = AD_HEADER_LEN;
363
364     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
365     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, 
366            sizeof( ad->ad_version ));
367
368     /* tag broken v1 headers. just assume they're all right. 
369      * we detect two cases: null magic/version
370      *                      byte swapped magic/version
371      * XXX: in the future, you'll need the v1compat flag. 
372      * (ad->ad_flags & ADFLAGS_V1COMPAT) */
373     if (!ad->ad_magic && !ad->ad_version) {
374       if (!warning) {
375         LOG(log_debug, logtype_default, "notice: fixing up null v1 magic/version.");
376         warning++;
377       }
378       ad->ad_magic = AD_MAGIC;
379       ad->ad_version = AD_VERSION1;
380
381     } else if ((ad->ad_magic == AD_MAGIC) && 
382                (ad->ad_version == AD_VERSION1)) {
383       if (!warning) {
384         LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
385         warning++;
386       }
387
388     } else {
389       ad->ad_magic = ntohl( ad->ad_magic );
390       ad->ad_version = ntohl( ad->ad_version );
391     }
392
393     if ((ad->ad_magic != AD_MAGIC) || ((ad->ad_version != AD_VERSION1)
394 #if AD_VERSION == AD_VERSION2
395                                        && (ad->ad_version != AD_VERSION2)
396 #endif /* AD_VERSION == AD_VERSION2 */
397                                        )) {
398       errno = EIO;
399       LOG(log_debug, logtype_default, "ad_open: can't parse AppleDouble header.");
400       return -1;
401     }
402
403     memcpy(ad->ad_filler, buf + ADEDOFF_FILLER, sizeof( ad->ad_filler ));
404     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
405     nentries = ntohs( nentries );
406
407     /* read in all the entry headers. if we have more than the 
408      * maximum, just hope that the rfork is specified early on. */
409     len = nentries*AD_ENTRY_LEN;
410 #ifdef USE_MMAPPED_HEADERS
411     if (len > sizeof(buf))
412       len = sizeof(buf);
413 #else /* USE_MMAPPED_HEADERS */
414     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
415       len = sizeof(ad->ad_data) - AD_HEADER_LEN;
416     buf += AD_HEADER_LEN;
417 #endif /* USE_MMAPPED_HEADERS */
418     if (read(ad->ad_hf.adf_fd, buf, len) != len) {
419         if (errno == 0)
420             errno = EIO;
421         LOG(log_debug, logtype_default, "ad_header_read: can't read entry info.");
422         return -1;
423     }
424     ad->ad_hf.adf_off += len;
425
426     /* figure out all of the entry offsets and lengths. if we aren't
427      * able to read a resource fork entry, bail. */
428     parse_entries(ad, buf, nentries);
429     if (!ad_getentryoff(ad, ADEID_RFORK)
430 #ifndef USE_MMAPPED_HEADERS
431         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
432 #endif /* ! USE_MMAPPED_HEADERS */
433         ) {
434       LOG(log_debug, logtype_default, "ad_header_read: problem with rfork entry offset."); 
435       return -1;
436     }
437
438     /* read/mmap up to the beginning of the resource fork. */
439 #ifdef USE_MMAPPED_HEADERS
440     ad->ad_data = mmap(NULL, ad_getentryoff(ad, ADEID_RFORK),
441                        PROT_READ | PROT_WRITE,
442                        (ad_getoflags(ad, ADFLAGS_HF) & O_RDWR) ? MAP_SHARED :
443                        MAP_PRIVATE, ad->ad_hf.adf_fd, 0);
444     if (ad->ad_data == MAP_FAILED) 
445       return -1;
446 #else /* USE_MMAPPED_HEADERS */
447     buf += len;
448     len = ad_getentryoff(ad, ADEID_RFORK) - ad->ad_hf.adf_off;
449     if (read(ad->ad_hf.adf_fd, buf, len) != len) {
450         if (errno == 0)
451             errno = EIO;
452         LOG(log_debug, logtype_default, "ad_header_read: can't read in entries.");
453         return -1;
454     }
455 #endif /* USE_MMAPPED_HEADERS */
456     
457     /* fix up broken dates */
458     if (ad->ad_version == AD_VERSION1) {
459       struct stat st;
460       u_int32_t aint;
461       
462       if (fstat(ad->ad_hf.adf_fd, &st) < 0) {
463         return 1; /* fail silently */
464       }
465       
466       /* check to see if the ad date is wrong. just see if we have
467       * a modification date in the future. */
468       if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
469           (aint > TIMEWARP_DELTA + st.st_mtime)) {
470         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
471         ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
472         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
473         ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
474         ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
475       }
476     }
477
478     return 0;
479 }
480
481
482 /*
483  * Put the .AppleDouble where it needs to be:
484  *
485  *          /   a/.AppleDouble/b
486  *      a/b
487  *          \   b/.AppleDouble/.Parent
488  */
489 char *
490 ad_path( path, adflags )
491     char        *path;
492     int         adflags;
493 {
494     static char pathbuf[ MAXPATHLEN + 1];
495     char        c, *slash, buf[MAXPATHLEN + 1];
496
497     strncpy(buf, path, MAXPATHLEN);
498     if ( adflags & ADFLAGS_DIR ) {
499         strncpy( pathbuf, buf, MAXPATHLEN );
500         if ( *buf != '\0' ) {
501             strcat( pathbuf, "/" );
502         }
503         slash = ".Parent";
504     } else {
505         if (( slash = strrchr( buf, '/' )) != NULL ) {
506             c = *++slash;
507             *slash = '\0';
508             strncpy( pathbuf, buf, MAXPATHLEN);
509             *slash = c;
510         } else {
511             pathbuf[ 0 ] = '\0';
512             slash = buf;
513         }
514     }
515     strncat( pathbuf, ".AppleDouble/", MAXPATHLEN - strlen(pathbuf));
516     strncat( pathbuf, slash, MAXPATHLEN - strlen(pathbuf));
517
518     return( pathbuf );
519 }
520
521 /*
522  * Support inherited protection modes for AppleDouble files.  The supplied
523  * mode is ANDed with the parent directory's mask value in lieu of "umask",
524  * and that value is returned.
525  */
526
527 #define DEFMASK 07700   /* be conservative */
528
529 char 
530 *ad_dir(path)
531     char                *path;
532 {
533     static char         modebuf[ MAXPATHLEN + 1];
534     char                *slash;
535
536     if ( strlen( path ) >= MAXPATHLEN ) {
537         return NULL;  /* can't do it */
538     }
539
540     /*
541      * For a path with directories in it, remove the final component
542      * (path or subdirectory name) to get the name we want to stat.
543      * For a path which is just a filename, use "." instead.
544      */
545     strcpy( modebuf, path );
546     if (( slash = strrchr( modebuf, '/' )) != NULL ) {
547         *slash = '\0';          /* remove pathname component */
548     } else {
549         modebuf[0] = '.';       /* use current directory */
550         modebuf[1] = '\0';
551     }
552     return modebuf;
553 }
554
555 int
556 ad_mode( path, mode )
557     char                *path;
558     int                 mode;
559 {
560     struct stat         stbuf;
561     char                *p;
562     
563     if ( mode == 0 ) {
564         return( mode );         /* save on syscalls */
565     }
566     p = ad_dir(path);
567     if (!p) {
568         return( mode & DEFMASK );  /* can't do it */
569     }
570
571     if ( stat( p, &stbuf ) != 0 ) {
572         return( mode & DEFMASK );       /* bail out... can't stat dir? */
573     }
574
575     return( mode & stbuf.st_mode );
576 }
577
578 /*
579  * Use mkdir() with mode bits taken from ad_mode().
580  */
581 int
582 ad_mkdir( path, mode )
583     char                *path;
584     int                 mode;
585 {
586 #ifdef DEBUG
587     LOG(log_info, logtype_default, "ad_mkdir: Creating directory with mode %d", mode);
588 #endif /* DEBUG */
589     return mkdir( path, ad_mode( path, mode ) );
590 }
591
592
593 /*
594  * It's not possible to open the header file O_RDONLY -- the read
595  * will fail and return an error. this refcounts things now. 
596  */
597 int ad_open( path, adflags, oflags, mode, ad )
598     char                *path;
599     int                 adflags, oflags, mode;
600     struct adouble      *ad;
601 {
602     const struct entry  *eid;
603     struct stat         st;
604     char                *slash, *ad_p;
605     int                 hoflags, admode;
606     u_int16_t           ashort;
607
608     if (ad->ad_inited != AD_INITED) {
609         ad_dfileno(ad) = -1;
610         ad_hfileno(ad) = -1;
611         adf_lock_init(&ad->ad_df);
612         adf_lock_init(&ad->ad_hf);
613 #ifdef USE_MMAPPED_HEADERS
614         ad->ad_data = MAP_FAILED;
615 #endif /* USE_MMAPPED_HEADERS */
616         ad->ad_inited = AD_INITED;
617         ad->ad_refcount = 1;
618     }
619
620     if (adflags & ADFLAGS_DF) { 
621         if (ad_dfileno(ad) == -1) {
622           hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
623           admode = ad_mode( path, mode ); 
624           if (( ad->ad_df.adf_fd = open( path, hoflags, admode )) < 0 ) {
625              if (errno == EACCES && !(oflags & O_RDWR)) {
626                 hoflags = oflags;
627                 ad->ad_df.adf_fd =open( path, hoflags, admode );
628              }
629           }
630           if ( ad->ad_df.adf_fd < 0)
631                 return -1;      
632           ad->ad_df.adf_off = 0;
633           ad->ad_df.adf_flags = hoflags;
634         } 
635         else {
636             /* the file is already open... but */
637             if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
638                 !(ad->ad_df.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
639             {
640                  errno == EACCES;
641                  return -1;
642             }
643         }
644         ad->ad_df.adf_refcount++;
645     }
646
647     if (adflags & ADFLAGS_HF) {
648         if (ad_hfileno(ad) == -1) {
649           ad_p = ad_path( path, adflags );
650
651           hoflags = oflags & ~O_CREAT;
652           hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
653           if (( ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 )) < 0 ) {
654             if (errno == EACCES && !(oflags & O_RDWR)) {
655                 hoflags = oflags & ~O_CREAT;
656                 ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
657             }    
658           }
659           if ( ad->ad_hf.adf_fd < 0 ) {
660             if (errno == ENOENT && (oflags & O_CREAT) ) {
661               /*
662                * We're expecting to create a new adouble header file,
663                * here.
664                * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
665                */
666               admode = ad_hf_mode(ad_mode( ad_p, mode )); 
667               errno = 0;
668               if (( ad->ad_hf.adf_fd = open( ad_p, oflags,
669                                              admode )) < 0 ) {
670                 /*
671                  * Probably .AppleDouble doesn't exist, try to
672                  * mkdir it.
673                  */
674                 if ((errno == ENOENT) && 
675                     ((adflags & ADFLAGS_NOADOUBLE) == 0)) {
676                   if (( slash = strrchr( ad_p, '/' )) == NULL ) {
677                     ad_close( ad, adflags );
678                     return( -1 );
679                   }
680                   *slash = '\0';
681                   errno = 0;
682                   if ( ad_mkdir( ad_p, 0777 ) < 0 ) {
683                     ad_close( ad, adflags );
684                     return( -1 );
685                   }
686                   *slash = '/';
687                   if (( ad->ad_hf.adf_fd = 
688                         open( ad_p, oflags, ad_mode( ad_p, mode) )) < 0 ) {
689                     ad_close( ad, adflags );
690                     return( -1 );
691                   }
692                 } else {
693                   ad_close( ad, adflags );
694                   return( -1 );
695                 }
696               }
697               ad->ad_hf.adf_flags = oflags;
698             } else {
699               ad_close( ad, adflags );
700               return( -1 );
701             }
702           } else if ((fstat(ad->ad_hf.adf_fd, &st) == 0) && 
703                      (st.st_size == 0)) {
704             /* for 0 length files, treat them as new. */
705             ad->ad_hf.adf_flags = (oflags & ~O_RDONLY) | O_RDWR;
706           } else {
707             ad->ad_hf.adf_flags = hoflags;
708           }
709           ad->ad_hf.adf_off = 0;
710           
711           /*
712            * This is a new adouble header file. Initialize the structure,
713            * instead of reading it.
714            */
715           memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
716           if ( ad->ad_hf.adf_flags & ( O_TRUNC | O_CREAT )) {
717             struct stat st;
718
719             ad->ad_magic = AD_MAGIC;
720             ad->ad_version = AD_VERSION;
721             memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
722
723 #ifdef USE_MMAPPED_HEADERS
724             /* truncate the header file and mmap it. */
725             ftruncate(ad->ad_hf.adf_fd, AD_DATASZ);
726             ad->ad_data = mmap(NULL, AD_DATASZ, PROT_READ | PROT_WRITE,
727                                MAP_SHARED, ad->ad_hf.adf_fd, 0);
728             if (ad->ad_data == MAP_FAILED) {
729               ad_close(ad, adflags);
730               return -1;
731             }       
732 #else /* USE_MMAPPED_HEADERS */
733             memset(ad->ad_data, 0, sizeof(ad->ad_data));
734 #endif /* USE_MMAPPED_HEADERS */
735
736             eid = entry_order;
737             while (eid->id) {
738               ad->ad_eid[eid->id].ade_off = eid->offset;
739               ad->ad_eid[eid->id].ade_len = eid->len;
740               eid++;
741             }
742             
743             /* put something sane in the directory finderinfo */
744             if (adflags & ADFLAGS_DIR) {
745               /* set default view */
746               ashort = htons(FINDERINFO_CLOSEDVIEW);
747               memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, 
748                      &ashort, sizeof(ashort));
749             } else {
750               /* set default creator/type fields */
751               memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,
752                      "TEXT", 4);
753               memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,
754                      "UNIX", 4);
755             }
756
757             /* make things invisible */
758             if ((*path == '.') && strcmp(path, ".") && strcmp(path, "..")) {
759               ashort = htons(ATTRBIT_INVISIBLE);
760               ad_setattr(ad, ashort);
761               ashort = htons(FINDERINFO_INVISIBLE);
762               memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,
763                      &ashort, sizeof(ashort));
764             }
765
766             /*if (gettimeofday(&tv, NULL) < 0) {
767               ad_close(ad, adflags);
768               return -1;
769             }*/
770
771             if (stat(path, &st) < 0) {
772                 ad_close(ad, adflags);
773                 return -1;
774             }
775             
776             /* put something sane in the date fields */
777             ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
778             ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
779             ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
780             ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
781
782           } else {
783             /*
784              * Read the adouble header in and parse it.
785              */
786             if ((ad_header_read( ad ) < 0)
787 #if AD_VERSION == AD_VERSION2
788                 || (ad_v1tov2(ad, ad_p) < 0)
789 #endif /* AD_VERSION == AD_VERSION2 */
790                 ) {
791               ad_close( ad, adflags );
792               return( -1 );
793             }
794           }
795         }
796         else { /* already open */
797             if ((oflags & ( O_RDWR | O_WRONLY)) &&             
798                 !(ad->ad_hf.adf_flags & ( O_RDWR | O_WRONLY))) {
799                 if (adflags & ADFLAGS_DF) {
800                     /* don't call with ADFLAGS_HF because we didn't open ressource fork */
801                     ad_close( ad, ADFLAGS_DF );
802                  }
803                  errno == EACCES;
804                  return -1;
805             }
806         }
807         ad->ad_hf.adf_refcount++;
808     }
809         
810     return( 0 );
811 }
812
813 /* to do this with mmap, we need the hfs fs to understand how to mmap
814    header files. */
815 int ad_refresh(struct adouble *ad)
816 {
817 #ifdef USE_MMAPPED_HEADERS
818   off_t off;
819 #endif /* USE_MMAPPED_HEADERS */
820
821   if (ad->ad_hf.adf_fd < -1)
822     return -1;
823
824 #ifdef USE_MMAPPED_HEADERS
825   if (ad->ad_data == MAP_FAILED)
826     return -1;
827   
828   /* re-read the header */
829   off = ad_getentryoff(ad, ADEID_RFORK);
830   memcpy(&nentries, ad->ad_data + ADEDOFF_NENTRIES, sizeof(nentries));
831   nentries = ntohs(nentries);
832   parse_entries(ad, ad->ad_data + AD_HEADER_LEN, nentries);
833
834   /* check to see if something screwy happened */
835   if (!ad_getentryoff(ad, ADEID_RFORK))
836     return -1;
837
838   /* if there's a length discrepancy, remap the header. this shouldn't
839    * really ever happen. */
840   if (off != ad_getentryoff(ad, ADEID_RFORK)) {
841     char *buf = ad->ad_data;
842     buf = ad->ad_data;
843     ad->ad_data = mmap(NULL, ad_getentryoff(ad, ADEID_RFORK), 
844                        PROT_READ | PROT_WRITE,
845                        (ad_getoflags(ad, ADFLAGS_HF) & O_RDWR) ? 
846                        MAP_SHARED : MAP_PRIVATE, ad->ad_hf.adf_fd, 0);
847     if (ad->ad_data == MAP_FAILED) {
848       ad->ad_data = buf;
849       return -1;
850     }
851     munmap(buf, off);
852   }
853   return 0;
854
855 #else /* USE_MMAPPED_HEADERS */
856   return ad_header_read(ad);
857 #endif /* USE_MMAPPED_HEADERS */
858 }