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