]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
5fd833d1205e73f6e279f9ae171c307e7d064877
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * $Id: ad_open.c,v 1.30.6.6 2004-02-06 13:39:52 bfernhomberg 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  * NOTE: I don't use inline because a good compiler should be
27  * able to optimize all the static below. Didier
28  */
29
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif /* HAVE_CONFIG_H */
33
34 #include <string.h>
35 #ifdef HAVE_FCNTL_H
36 #include <fcntl.h>
37 #endif /* HAVE_FCNTL_H */
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif /* HAVE_UNISTD_H */
41 #include <errno.h>
42 #include <atalk/logger.h>
43
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/param.h>
48 #include <sys/mman.h>
49
50 #include <netatalk/endian.h>
51 #include <atalk/adouble.h>
52 #include <atalk/util.h>
53
54 #include "ad_private.h"
55
56 #ifndef MAX
57 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
58 #endif /* ! MAX */
59
60 /*
61  * AppleDouble entry default offsets.
62  * The layout looks like this:
63  *
64  * this is the v1 layout:
65  *        255     200             16      32              N
66  *      |  NAME |    COMMENT    | FILEI |    FINDERI    | RFORK |
67  *
68  * we need to change it to look like this:
69  *
70  * v2 layout:
71  * field       length (in bytes)
72  * NAME        255
73  * COMMENT     200
74  * FILEDATESI  16     replaces FILEI
75  * FINDERI     32  
76  * DID          4     new
77  * AFPFILEI     4     new
78  * SHORTNAME   12     8.3 new
79  * RFORK        N
80  * 
81  * so, all we need to do is replace FILEI with FILEDATESI, move RFORK,
82  * and add in the new fields.
83  *
84  * NOTE: the HFS module will need similar modifications to interact with
85  * afpd correctly.
86  */
87  
88 #define ADEDOFF_MAGIC        (0)
89 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
90 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
91 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
92
93 /* initial lengths of some of the fields */
94 #define ADEDLEN_INIT     0
95
96 /* make sure we don't redefine ADEDOFF_FILEI */
97 #ifdef ADEDOFF_FILEI
98 #undef ADEDOFF_FILEI
99 #endif /* ADEDOFF_FILEI */
100
101 #define ADEDOFF_NAME_V1      (AD_HEADER_LEN + ADEID_NUM_V1*AD_ENTRY_LEN)
102 #define ADEDOFF_COMMENT_V1   (ADEDOFF_NAME_V1 + ADEDLEN_NAME)
103 #define ADEDOFF_FILEI        (ADEDOFF_COMMENT_V1 + ADEDLEN_COMMENT)
104 #define ADEDOFF_FINDERI_V1   (ADEDOFF_FILEI + ADEDLEN_FILEI)
105 #define ADEDOFF_RFORK_V1     (ADEDOFF_FINDERI_V1 + ADEDLEN_FINDERI)
106
107 /* i stick things in a slightly different order than their eid order in 
108  * case i ever want to separate RootInfo behaviour from the rest of the 
109  * stuff. */
110 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
111 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
112 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
113 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
114 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
115 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
116 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
117 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
118 #define ADEDOFF_PRIVDEV      (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
119 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
120 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
121 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
122
123 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
124
125 /* we keep local copies of a bunch of stuff so that we can initialize things 
126  * correctly. */
127
128 /* Bits in the finderinfo data. 
129  * see etc/afpd/{directory.c,file.c} for the finderinfo structure
130  * layout. */
131 #define FINDERINFO_CUSTOMICON 0x4
132 #define FINDERINFO_CLOSEDVIEW 0x100
133
134 /* offsets in finderinfo */
135 #define FINDERINFO_FRTYPEOFF   0
136 #define FINDERINFO_FRCREATOFF  4
137 #define FINDERINFO_FRFLAGOFF   8
138 #define FINDERINFO_FRVIEWOFF  14
139
140 /* invisible bit for dot files */
141 #define ATTRBIT_INVISIBLE     (1 << 0)
142 #define FINDERINFO_INVISIBLE  (1 << 14)
143
144 /* this is to prevent changing timezones from causing problems with
145    localtime volumes. the screw-up is 30 years. we use a delta of 5
146    years.  */
147 #define TIMEWARP_DELTA 157680000
148
149
150 struct entry {
151   u_int32_t id, offset, len;
152 };
153
154 static const struct entry entry_order1[ADEID_NUM_V1 +1] = {
155   {ADEID_NAME,    ADEDOFF_NAME_V1,    ADEDLEN_INIT},      /* 3 */
156   {ADEID_COMMENT, ADEDOFF_COMMENT_V1, ADEDLEN_INIT},      /* 4 */
157   {ADEID_FILEI,   ADEDOFF_FILEI,      ADEDLEN_FILEI},     /* 7 */
158   {ADEID_FINDERI, ADEDOFF_FINDERI_V1, ADEDLEN_FINDERI},   /* 9 */
159   {ADEID_RFORK,   ADEDOFF_RFORK_V1,   ADEDLEN_INIT},      /* 2 */
160   {0, 0, 0}
161 };
162
163 #if AD_VERSION == AD_VERSION1 
164 #define DISK_EID(ad, a) (a)
165
166 #else /* AD_VERSION == AD_VERSION2 */
167
168 static u_int32_t get_eid(struct adouble *ad, u_int32_t eid) 
169 {
170     if (eid <= 15)
171         return eid;
172     if (ad->ad_version == AD_VERSION1)
173         return 0;
174     if (eid == AD_DEV)
175         return ADEID_PRIVDEV;
176     if (eid == AD_INO)
177         return ADEID_PRIVINO;
178     if (eid == AD_SYN)
179         return ADEID_PRIVSYN;
180     if (eid == AD_ID)
181         return ADEID_PRIVID;
182
183     return 0;
184 }
185
186 #define DISK_EID(ad, a) get_eid(ad, a)
187
188 static const struct entry entry_order2[ADEID_NUM_V2 +1] = {
189   {ADEID_NAME, ADEDOFF_NAME_V2, ADEDLEN_INIT},
190   {ADEID_COMMENT, ADEDOFF_COMMENT_V2, ADEDLEN_INIT},
191   {ADEID_FILEDATESI, ADEDOFF_FILEDATESI, ADEDLEN_FILEDATESI},
192   {ADEID_FINDERI, ADEDOFF_FINDERI_V2, ADEDLEN_FINDERI},
193   {ADEID_DID, ADEDOFF_DID, ADEDLEN_DID},
194   {ADEID_AFPFILEI, ADEDOFF_AFPFILEI, ADEDLEN_AFPFILEI},
195   {ADEID_SHORTNAME, ADEDOFF_SHORTNAME, ADEDLEN_INIT},
196   {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
197   {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV, ADEDLEN_INIT},
198   {ADEID_PRIVINO,     ADEDOFF_PRIVINO, ADEDLEN_INIT},
199   {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN, ADEDLEN_INIT},
200   {ADEID_PRIVID,     ADEDOFF_PRIVID, ADEDLEN_INIT},
201   {ADEID_RFORK, ADEDOFF_RFORK_V2, ADEDLEN_INIT},
202
203   {0, 0, 0}
204 };
205 #endif /* AD_VERSION == AD_VERSION2 */
206
207 #if AD_VERSION == AD_VERSION2
208
209 static int ad_update(struct adouble *ad, const char *path)
210 {
211   struct stat st;
212   u_int16_t nentries = 0;
213   off_t     off, shiftdata=0;
214   const struct entry  *eid;
215   static off_t entry_len[ADEID_MAX];
216   static char  databuf[ADEID_MAX][256], *buf;
217   int fd;
218
219   /* check to see if we should convert this header. */
220   if (!path || (ad->ad_version != AD_VERSION2))
221     return 0;
222   
223   if (ad->ad_eid[ADEID_RFORK].ade_off)  
224     shiftdata = ADEDOFF_RFORK_V2 -ad->ad_eid[ADEID_RFORK].ade_off;
225
226   memcpy(&nentries, ad->ad_data + ADEDOFF_NENTRIES, sizeof( nentries ));
227   nentries = ntohs( nentries );
228
229   if ( shiftdata == 0 && nentries == ADEID_NUM_V2)
230     return 0;
231
232   memset(entry_len, 0, sizeof(entry_len));
233   memset(databuf, 0, sizeof(databuf));
234
235   /* bail if we can't get a lock */
236   if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0)
237     goto bail_err;
238
239   if ((fd = open(path, O_RDWR)) < 0)
240     goto bail_lock;
241
242   if (fstat(fd, &st) ||
243     sys_ftruncate(fd, st.st_size + shiftdata) < 0) {
244     goto bail_open;
245   }
246   if (st.st_size > 0x7fffffff) {
247     LOG(log_debug, logtype_default, "ad_update: file '%s' too big for update.", path);
248     goto bail_truncate;
249   }
250   /* last place for failure. */
251   if ((void *) (buf = (char *)
252                 mmap(NULL, st.st_size + shiftdata,
253                      PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
254           MAP_FAILED) {
255     goto bail_truncate;
256   }
257
258   off = ad->ad_eid[ADEID_RFORK].ade_off;
259
260   /* move the RFORK. this assumes that the RFORK is at the end */
261   if (off) {
262     memmove(buf + ADEDOFF_RFORK_V2, buf + off, ad->ad_eid[ADEID_RFORK].ade_len);
263   }
264
265   munmap(buf, st.st_size + shiftdata);
266   close(fd);
267
268   /* now, fix up our copy of the header */
269   memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
270  
271   /* save the header entries */ 
272   eid = entry_order2;
273   while (eid->id) {
274     if( ad->ad_eid[eid->id].ade_off != 0) {
275       if ( eid->id > 2 && ad->ad_eid[eid->id].ade_len < 256)
276         memcpy( databuf[eid->id], ad->ad_data +ad->ad_eid[eid->id].ade_off, ad->ad_eid[eid->id].ade_len);
277       entry_len[eid->id] = ad->ad_eid[eid->id].ade_len;
278     }
279     eid++;
280   }
281
282   memset(ad->ad_data + AD_HEADER_LEN, 0, AD_DATASZ - AD_HEADER_LEN);
283
284   /* copy the saved entries to the new header */
285   eid = entry_order2;
286   while (eid->id) {
287     if ( eid->id > 2 && entry_len[eid->id] > 0) {
288       memcpy(ad->ad_data+eid->offset, databuf[eid->id], entry_len[eid->id]);
289     }
290     ad->ad_eid[eid->id].ade_off = eid->offset;
291     ad->ad_eid[eid->id].ade_len = entry_len[eid->id];
292     eid++;
293   }
294
295   /* rebuild the header and cleanup */
296   ad_flush(ad, ADFLAGS_HF );
297   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
298
299   LOG(log_debug, logtype_default, "updated AD2 header %s", path);
300
301   return 0;
302
303 bail_truncate:
304   sys_ftruncate(fd, st.st_size);
305 bail_open:
306   close(fd);
307 bail_lock:
308   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
309 bail_err:
310   return -1;
311 }
312
313
314 /* FIXME work only if < 2GB */
315 static int ad_v1tov2(struct adouble *ad, const char *path)
316 {
317   struct stat st;
318   u_int16_t attr;
319   char *buf;
320   int fd, off;
321   /* use resource fork offset from file */
322   int shiftdata;
323   
324   /* check to see if we should convert this header. */
325   if (!path || (ad->ad_version != AD_VERSION1))
326     return 0;
327
328   /* we want version1 anyway */
329   if (ad->ad_flags == AD_VERSION1)
330       return 0;
331
332
333   if (!ad->ad_flags) {
334       /* we don't really know what we want */
335       ad->ad_flags = ad->ad_version;
336       return 0;
337   }
338
339   /* convert from v1 to v2. what does this mean?
340    *  1) change FILEI into FILEDATESI
341    *  2) create space for SHORTNAME, AFPFILEI, DID, and PRODOSI
342    *  3) move FILEI attributes into AFPFILEI
343    *  4) initialize ACCESS field of FILEDATESI.
344    *  5) move the resource fork
345    */
346   
347   /* bail if we can't get a lock */
348   if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0) 
349     goto bail_err;
350   
351   if ((fd = open(path, O_RDWR)) < 0) 
352     goto bail_lock;
353
354   if (ad->ad_eid[ADEID_RFORK].ade_off) {
355       shiftdata = ADEDOFF_RFORK_V2 -ad->ad_eid[ADEID_RFORK].ade_off;
356   }
357   else {
358       shiftdata = ADEDOFF_RFORK_V2 -ADEDOFF_RFORK_V1; /* 136 */
359   }
360
361   if (fstat(fd, &st) ||
362       sys_ftruncate(fd, st.st_size + shiftdata) < 0) {
363     goto bail_open;
364   }
365   if (st.st_size > 0x7fffffff) {
366       LOG(log_debug, logtype_default, "ad_v1tov2: file too big."); 
367       goto bail_truncate;
368   }
369   
370   /* last place for failure. */
371   if ((void *) (buf = (char *) 
372                 mmap(NULL, st.st_size + shiftdata,
373                      PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == 
374           MAP_FAILED) {
375     goto bail_truncate;
376   }
377   
378   off = ad->ad_eid[ADEID_RFORK].ade_off;
379
380   /* move the RFORK. this assumes that the RFORK is at the end */
381   if (off) {
382       memmove(buf + ADEDOFF_RFORK_V2, buf + off, ad->ad_eid[ADEID_RFORK].ade_len);
383   }
384
385   munmap(buf, st.st_size + shiftdata);
386   close(fd);
387
388   /* now, fix up our copy of the header */
389   memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
390   
391   /* replace FILEI with FILEDATESI */
392   ad_getattr(ad, &attr);
393   ad->ad_eid[ADEID_FILEDATESI].ade_off = ADEDOFF_FILEDATESI;
394   ad->ad_eid[ADEID_FILEDATESI].ade_len = ADEDLEN_FILEDATESI;
395   ad->ad_eid[ADEID_FILEI].ade_off = 0;
396   ad->ad_eid[ADEID_FILEI].ade_len = 0;
397   
398   /* add in the new entries */
399   ad->ad_eid[ADEID_DID].ade_off = ADEDOFF_DID;
400   ad->ad_eid[ADEID_DID].ade_len = ADEDLEN_DID;
401   ad->ad_eid[ADEID_AFPFILEI].ade_off = ADEDOFF_AFPFILEI;
402   ad->ad_eid[ADEID_AFPFILEI].ade_len = ADEDLEN_AFPFILEI;
403   ad->ad_eid[ADEID_SHORTNAME].ade_off = ADEDOFF_SHORTNAME;
404   ad->ad_eid[ADEID_SHORTNAME].ade_len = ADEDLEN_INIT;
405   ad->ad_eid[ADEID_PRODOSFILEI].ade_off = ADEDOFF_PRODOSFILEI;
406   ad->ad_eid[ADEID_PRODOSFILEI].ade_len = ADEDLEN_PRODOSFILEI;
407   
408   ad->ad_eid[ADEID_PRIVDEV].ade_off = ADEDOFF_PRIVDEV;
409   ad->ad_eid[ADEID_PRIVDEV].ade_len = ADEDLEN_INIT;
410   ad->ad_eid[ADEID_PRIVINO].ade_off = ADEDOFF_PRIVINO;
411   ad->ad_eid[ADEID_PRIVINO].ade_len = ADEDLEN_INIT;
412   ad->ad_eid[ADEID_PRIVSYN].ade_off = ADEDOFF_PRIVSYN;
413   ad->ad_eid[ADEID_PRIVSYN].ade_len = ADEDLEN_INIT;
414   ad->ad_eid[ADEID_PRIVID].ade_off  = ADEDOFF_PRIVID;
415   ad->ad_eid[ADEID_PRIVID].ade_len =  ADEDLEN_INIT;
416   
417   /* shift the old entries (NAME, COMMENT, FINDERI, RFORK) */
418   ad->ad_eid[ADEID_NAME].ade_off = ADEDOFF_NAME_V2;
419   ad->ad_eid[ADEID_COMMENT].ade_off = ADEDOFF_COMMENT_V2;
420   ad->ad_eid[ADEID_FINDERI].ade_off = ADEDOFF_FINDERI_V2;
421   ad->ad_eid[ADEID_RFORK].ade_off = ADEDOFF_RFORK_V2;
422   
423   /* switch to v2 */
424   ad->ad_version = AD_VERSION2;
425   
426   /* move our data buffer to make space for the new entries. */
427   memmove(ad->ad_data + ADEDOFF_NAME_V2, ad->ad_data + ADEDOFF_NAME_V1,
428           ADEDOFF_RFORK_V1 - ADEDOFF_NAME_V1);
429   
430   /* now, fill in the space with appropriate stuff. we're
431      operating as a v2 file now. */
432   ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
433   memset(ad_entry(ad, ADEID_DID), 0, ADEDLEN_DID);
434   memset(ad_entry(ad, ADEID_AFPFILEI), 0, ADEDLEN_AFPFILEI);
435   ad_setattr(ad, attr);
436   memset(ad_entry(ad, ADEID_SHORTNAME), 0, ADEDLEN_SHORTNAME);
437   memset(ad_entry(ad, ADEID_PRODOSFILEI), 0, ADEDLEN_PRODOSFILEI);
438   
439   /* rebuild the header and cleanup */
440   ad_flush(ad, ADFLAGS_HF );
441   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
442
443   return 0;
444   
445 bail_truncate:
446   sys_ftruncate(fd, st.st_size);
447 bail_open:
448   close(fd);
449 bail_lock:
450   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
451 bail_err:
452   return -1;
453 }
454 #endif /* AD_VERSION == AD_VERSION2 */
455
456 #ifdef ATACC
457 mode_t ad_hf_mode (mode_t mode)
458 {
459     /* fnctl lock need write access */
460     if ((mode & S_IRUSR))
461         mode |= S_IWUSR;
462     if ((mode & S_IRGRP))
463         mode |= S_IWGRP;
464     if ((mode & S_IROTH))
465         mode |= S_IWOTH;
466     /* if write mode set add read mode */
467     if ((mode & S_IWUSR))
468         mode |= S_IRUSR;
469     if ((mode & S_IWGRP))
470         mode |= S_IRGRP;
471     if ((mode & S_IWOTH))
472         mode |= S_IROTH;
473
474     return mode;
475 }
476
477 #endif
478
479 /* ------------------------------------- 
480   read in the entries 
481 */
482 static void parse_entries(struct adouble *ad, char *buf,
483                                     u_int16_t nentries)
484 {
485     u_int32_t   eid, len, off;
486     int         warning = 0;
487
488     /* now, read in the entry bits */
489     for (; nentries > 0; nentries-- ) {
490         memcpy(&eid, buf, sizeof( eid ));
491         eid = DISK_EID(ad, ntohl( eid ));
492         buf += sizeof( eid );
493         memcpy(&off, buf, sizeof( off ));
494         off = ntohl( off );
495         buf += sizeof( off );
496         memcpy(&len, buf, sizeof( len ));
497         len = ntohl( len );
498         buf += sizeof( len );
499
500         if ( 0 < eid && eid < ADEID_MAX ) {
501             ad->ad_eid[ eid ].ade_off = off;
502             ad->ad_eid[ eid ].ade_len = len;
503         } else if (!warning) {
504             warning = 1;
505             LOG(log_debug, logtype_default, "ad_refresh: nentries %hd  eid %d\n",
506                     nentries, eid );
507         }
508     }
509 }
510
511
512 /* this reads enough of the header so that we can figure out all of
513  * the entry lengths and offsets. once that's done, we just read/mmap
514  * the rest of the header in.
515  *
516  * NOTE: we're assuming that the resource fork is kept at the end of
517  *       the file. also, mmapping won't work for the hfs fs until it
518  *       understands how to mmap header files. */
519 static int ad_header_read(struct adouble *ad, struct stat *hst)
520 {
521     char                *buf = ad->ad_data;
522     u_int16_t           nentries;
523     int                 len;
524     ssize_t             header_len;
525     static int          warning = 0;
526     struct stat         st;
527
528     /* read the header */
529     if ((header_len = adf_pread( &ad->ad_hf, buf, sizeof(ad->ad_data), 0)) < 0) {
530         return -1;
531     }
532     if (header_len < AD_HEADER_LEN) {
533         errno = EIO;
534         return -1;
535     }
536
537     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
538     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
539
540     /* tag broken v1 headers. just assume they're all right. 
541      * we detect two cases: null magic/version
542      *                      byte swapped magic/version
543      * XXX: in the future, you'll need the v1compat flag. 
544      * (ad->ad_flags & ADFLAGS_V1COMPAT) */
545     if (!ad->ad_magic && !ad->ad_version) {
546       if (!warning) {
547         LOG(log_debug, logtype_default, "notice: fixing up null v1 magic/version.");
548         warning++;
549       }
550       ad->ad_magic = AD_MAGIC;
551       ad->ad_version = AD_VERSION1;
552
553     } else if (ad->ad_magic == AD_MAGIC && ad->ad_version == AD_VERSION1) {
554       if (!warning) {
555         LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
556         warning++;
557       }
558
559     } else {
560       ad->ad_magic = ntohl( ad->ad_magic );
561       ad->ad_version = ntohl( ad->ad_version );
562     }
563
564     if ((ad->ad_magic != AD_MAGIC) || ((ad->ad_version != AD_VERSION1)
565 #if AD_VERSION == AD_VERSION2
566                                        && (ad->ad_version != AD_VERSION2)
567 #endif /* AD_VERSION == AD_VERSION2 */
568                                        )) {
569       errno = EIO;
570       LOG(log_debug, logtype_default, "ad_open: can't parse AppleDouble header.");
571       return -1;
572     }
573
574     memcpy(ad->ad_filler, buf + ADEDOFF_FILLER, sizeof( ad->ad_filler ));
575     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
576     nentries = ntohs( nentries );
577
578     /* read in all the entry headers. if we have more than the 
579      * maximum, just hope that the rfork is specified early on. */
580     len = nentries*AD_ENTRY_LEN;
581
582     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
583       len = sizeof(ad->ad_data) - AD_HEADER_LEN;
584
585     buf += AD_HEADER_LEN;
586     if (len > header_len - AD_HEADER_LEN) {
587         errno = EIO;
588         LOG(log_debug, logtype_default, "ad_header_read: can't read entry info.");
589         return -1;
590     }
591
592     /* figure out all of the entry offsets and lengths. if we aren't
593      * able to read a resource fork entry, bail. */
594     nentries = len / AD_ENTRY_LEN;
595     parse_entries(ad, buf, nentries);
596     if (!ad_getentryoff(ad, ADEID_RFORK)
597         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
598         ) {
599       LOG(log_debug, logtype_default, "ad_header_read: problem with rfork entry offset."); 
600       return -1;
601     }
602
603     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
604         errno = EIO;
605         LOG(log_debug, logtype_default, "ad_header_read: can't read in entries.");
606         return -1;
607     }
608     
609     if (hst == NULL) {
610         hst = &st;
611         if (fstat(ad->ad_hf.adf_fd, &st) < 0) {
612             return 1; /* fail silently */
613          }
614     }
615     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
616
617     /* fix up broken dates */
618     if (ad->ad_version == AD_VERSION1) {
619       u_int32_t aint;
620       
621       /* check to see if the ad date is wrong. just see if we have
622       * a modification date in the future. */
623       if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
624           (aint > TIMEWARP_DELTA + hst->st_mtime)) {
625         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
626         ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
627         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
628         ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
629         ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
630       }
631     }
632
633     return 0;
634 }
635
636
637 /*
638  * Put the .AppleDouble where it needs to be:
639  *
640  *          /   a/.AppleDouble/b
641  *      a/b
642  *          \   b/.AppleDouble/.Parent
643  */
644 char *
645 ad_path( path, adflags )
646     const char  *path;
647     int         adflags;
648 {
649     static char pathbuf[ MAXPATHLEN + 1];
650     char        c, *slash, buf[MAXPATHLEN + 1];
651
652     strncpy(buf, path, MAXPATHLEN);
653     if ( adflags & ADFLAGS_DIR ) {
654         strncpy( pathbuf, buf, MAXPATHLEN );
655         if ( *buf != '\0' ) {
656             strcat( pathbuf, "/" );
657         }
658         slash = ".Parent";
659     } else {
660         if (NULL != ( slash = strrchr( buf, '/' )) ) {
661             c = *++slash;
662             *slash = '\0';
663             strncpy( pathbuf, buf, MAXPATHLEN);
664             *slash = c;
665         } else {
666             pathbuf[ 0 ] = '\0';
667             slash = buf;
668         }
669     }
670     strncat( pathbuf, ".AppleDouble/", MAXPATHLEN - strlen(pathbuf));
671     strncat( pathbuf, slash, MAXPATHLEN - strlen(pathbuf));
672
673     return( pathbuf );
674 }
675
676 /*
677  * Support inherited protection modes for AppleDouble files.  The supplied
678  * mode is ANDed with the parent directory's mask value in lieu of "umask",
679  * and that value is returned.
680  */
681
682 #define DEFMASK 07700   /* be conservative */
683
684 char 
685 *ad_dir(path)
686     const char          *path;
687 {
688     static char         modebuf[ MAXPATHLEN + 1];
689     char                *slash;
690     size_t              len;
691
692     if ( (len = strlen( path )) >= MAXPATHLEN ) {
693         errno = ENAMETOOLONG;
694         return NULL;  /* can't do it */
695     }
696
697     /*
698      * For a path with directories in it, remove the final component
699      * (path or subdirectory name) to get the name we want to stat.
700      * For a path which is just a filename, use "." instead.
701      */
702     strcpy( modebuf, path );
703     slash = strrchr( modebuf, '/' );
704     /* is last char a '/' */
705     if (slash && slash[1] == 0) {
706         while (modebuf < slash && slash[-1] == '/') {
707             --slash;
708         }
709         if (modebuf < slash) {
710             *slash = '\0';              /* remove pathname component */
711             slash = strrchr( modebuf, '/' );
712         }
713     }
714     if (slash) {
715         *slash = '\0';          /* remove pathname component */
716     } else {
717         modebuf[0] = '.';       /* use current directory */
718         modebuf[1] = '\0';
719     }
720     return modebuf;
721 }
722
723 /* ---------------- */
724 static uid_t default_uid = -1;
725
726 int ad_setfuid(const uid_t id)
727 {
728     default_uid = id;
729     return 0;
730 }
731
732 /* ---------------- */
733 uid_t ad_getfuid(void) 
734 {
735     return default_uid;
736 }
737
738 /* ---------------- 
739    return inode of path parent directory
740 */
741 int ad_stat(const char *path, struct stat *stbuf)
742 {
743     char                *p;
744
745     p = ad_dir(path);
746     if (!p) {
747         return -1;
748     }
749
750     return stat( p, stbuf );
751 }
752
753 /* ---------------- 
754    if we are root change path user/ group
755    It can be a native function for BSD cf. FAQ.Q10
756    path:  pathname to chown 
757    stbuf: parent directory inode
758    
759    use fstat and fchown or lchown with linux?
760 */
761 #define EMULATE_SUIDDIR
762  
763 static int ad_chown(const char *path, struct stat *stbuf)
764 {
765 int ret = 0;
766 #ifdef EMULATE_SUIDDIR
767 uid_t id;
768
769     if (default_uid != -1) {  
770         /* we are root (admin) */
771         id = (default_uid)?default_uid:stbuf->st_uid;
772         ret = chown( path, id, stbuf->st_gid );
773     }
774 #endif    
775     return ret;
776 }
777
778 /* ---------------- 
779    return access right and inode of path parent directory
780 */
781 static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
782 {
783     if (*mode == 0) {
784        return -1;
785     }
786     if (ad_stat(path, stbuf) != 0) {
787         *mode &= DEFMASK;
788         return -1;
789     }
790     *mode &= stbuf->st_mode;
791     return 0;    
792 }
793
794 /* ---------------- 
795    return access right of path parent directory
796 */
797 int
798 ad_mode( path, mode )
799     const char          *path;
800     int                 mode;
801 {
802     struct stat         stbuf;
803     ad_mode_st(path, &mode, &stbuf);
804     return mode;
805 }
806
807 /*
808  * Use mkdir() with mode bits taken from ad_mode().
809  */
810 int
811 ad_mkdir( path, mode )
812     const char          *path;
813     int                 mode;
814 {
815 int ret;
816 int st_invalid;
817 struct stat stbuf;
818
819 #ifdef DEBUG
820     LOG(log_info, logtype_default, "ad_mkdir: Creating directory with mode %d", mode);
821 #endif /* DEBUG */
822
823     st_invalid = ad_mode_st(path, &mode, &stbuf);
824     ret = mkdir( path, mode );
825     if (ret || st_invalid)
826         return ret;
827     ad_chown(path, &stbuf);
828
829     return ret;    
830 }
831
832 /* ----------------- */
833 static int ad_error(struct adouble *ad, int adflags)
834 {
835     if ((adflags & ADFLAGS_NOHF)) {
836         /* FIXME double check : set header offset ?*/
837         return 0;
838     }
839     if ((adflags & ADFLAGS_DF)) {
840         ad_close( ad, ADFLAGS_DF );
841     }
842     return -1 ;
843 }
844
845 static int new_rfork(const char *path, struct adouble *ad, int adflags);
846
847 #ifdef  HAVE_PREAD
848 #define AD_SET(a) 
849 #else 
850 #define AD_SET(a) a = 0
851 #endif
852
853 void ad_init(struct adouble *ad, int flags)
854 {
855     memset( ad, 0, sizeof( struct adouble ) );
856     ad->ad_flags = flags;
857 }
858
859 /* -------------------
860  * It's not possible to open the header file O_RDONLY -- the read
861  * will fail and return an error. this refcounts things now. 
862  */
863 int ad_open( path, adflags, oflags, mode, ad )
864     const char          *path;
865     int                 adflags, oflags, mode;
866     struct adouble      *ad;
867 {
868     struct stat         st;
869     char                *slash, *ad_p;
870     int                 hoflags, admode;
871     int                 st_invalid;
872     int                 open_df = 0;
873     
874     if (ad->ad_inited != AD_INITED) {
875         ad_dfileno(ad) = -1;
876         ad_hfileno(ad) = -1;
877         adf_lock_init(&ad->ad_df);
878         adf_lock_init(&ad->ad_hf);
879         ad->ad_inited = AD_INITED;
880         ad->ad_refcount = 1;
881     }
882
883     if ((adflags & ADFLAGS_DF)) { 
884         if (ad_dfileno(ad) == -1) {
885           hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
886           admode = mode;
887           st_invalid = ad_mode_st(path, &admode, &st);
888           ad->ad_df.adf_fd =open( path, hoflags, admode );
889           if (ad->ad_df.adf_fd < 0 ) {
890              if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
891                 hoflags = oflags;
892                 ad->ad_df.adf_fd =open( path, hoflags, admode );
893              }
894           }
895           if ( ad->ad_df.adf_fd < 0)
896                 return -1;
897
898           AD_SET(ad->ad_df.adf_off);
899           ad->ad_df.adf_flags = hoflags;
900           if ((oflags & O_CREAT) && !st_invalid) {
901               /* just created, set owner if admin (root) */
902               ad_chown(path, &st);
903           }
904         } 
905         else {
906             /* the file is already open... but */
907             if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
908                 !(ad->ad_df.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
909             {
910                  errno = EACCES;
911                  return -1;
912             }
913             /* FIXME 
914              * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
915              * already open. Should we check for it? ie
916              * O_EXCL --> error 
917              * O_TRUNC --> truncate the fork.
918              * idem for ressource fork.
919              */
920         }
921         open_df = ADFLAGS_DF;
922         ad->ad_df.adf_refcount++;
923     }
924
925     if (!(adflags & ADFLAGS_HF)) 
926         return 0;
927         
928     if (ad_hfileno(ad) != -1) { /* the file is already open */
929         if ((oflags & ( O_RDWR | O_WRONLY)) &&             
930                 !(ad->ad_hf.adf_flags & ( O_RDWR | O_WRONLY))) {
931             if (open_df) {
932                 /* don't call with ADFLAGS_HF because we didn't open ressource fork */
933                 ad_close( ad, open_df );
934             }
935             errno = EACCES;
936             return -1;
937         }
938         ad_refresh(ad);
939         ad->ad_hf.adf_refcount++;
940         return 0;
941     }
942
943     ad_p = ad_path( path, adflags );
944
945     hoflags = oflags & ~O_CREAT;
946     hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
947     ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
948     if (ad->ad_hf.adf_fd < 0 ) {
949         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
950             hoflags = oflags & ~O_CREAT;
951             ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
952         }    
953     }
954
955     if ( ad->ad_hf.adf_fd < 0 ) { 
956         if (errno == ENOENT && (oflags & O_CREAT) ) {
957             /*
958              * We're expecting to create a new adouble header file,
959              * here.
960              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
961              */
962             admode = mode;
963             st_invalid = ad_mode_st(ad_p, &admode, &st);
964             admode = ad_hf_mode(admode); 
965             errno = 0;
966             ad->ad_hf.adf_fd = open( ad_p, oflags,admode );
967             if ( ad->ad_hf.adf_fd < 0 ) {
968                 /*
969                  * Probably .AppleDouble doesn't exist, try to
970                  * mkdir it.
971                  */
972                 if (errno == ENOENT && (adflags & ADFLAGS_NOADOUBLE) == 0) {
973                     if (NULL == ( slash = strrchr( ad_p, '/' )) ) {
974                         return ad_error(ad, adflags);
975                     }
976                     *slash = '\0';
977                     errno = 0;
978                     if ( ad_mkdir( ad_p, 0777 ) < 0 ) {
979                         return ad_error(ad, adflags);
980                     }
981                     *slash = '/';
982                     admode = mode;
983                     st_invalid = ad_mode_st(ad_p, &admode, &st);
984                     admode = ad_hf_mode(admode); 
985                     ad->ad_hf.adf_fd = open( ad_p, oflags, admode);
986                     if ( ad->ad_hf.adf_fd < 0 ) {
987                         return ad_error(ad, adflags);
988                     }
989                 } else {
990                      return ad_error(ad, adflags);
991                 }
992             }
993             ad->ad_hf.adf_flags = oflags;
994             /* just created, set owner if admin owner (root) */
995             if (!st_invalid) {
996                 ad_chown(path, &st);
997             }
998         }
999         else {
1000             return ad_error(ad, adflags);
1001         }
1002     } else if (fstat(ad->ad_hf.adf_fd, &st) == 0 && st.st_size == 0) {
1003         /* for 0 length files, treat them as new. */
1004         ad->ad_hf.adf_flags = hoflags| O_TRUNC;
1005     } else {
1006         ad->ad_hf.adf_flags = hoflags;
1007     }
1008     AD_SET(ad->ad_hf.adf_off);
1009           
1010     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
1011     ad->ad_hf.adf_refcount++;
1012     if ((ad->ad_hf.adf_flags & ( O_TRUNC | O_CREAT ))) {
1013         /*
1014          * This is a new adouble header file. Initialize the structure,
1015          * instead of reading it.
1016         */
1017         if (new_rfork(path, ad, adflags) < 0) {
1018             /* the file is already deleted, perm, whatever, so return an error*/
1019             ad_close(ad, adflags);
1020             return -1;
1021         }
1022     } else {
1023             /* Read the adouble header in and parse it.*/
1024         if ((ad_header_read( ad , &st) < 0)
1025 #if AD_VERSION == AD_VERSION2
1026                 || (ad_v1tov2(ad, ad_p) < 0) || (ad_update(ad, ad_p) < 0)
1027 #endif /* AD_VERSION == AD_VERSION2 */
1028         ) {
1029             ad_close( ad, adflags );
1030             return( -1 );
1031         }
1032     }
1033     return 0 ;
1034 }
1035
1036 /* ----------------------------------- */
1037 static int new_rfork(const char *path, struct adouble *ad, int adflags)
1038 {
1039 #if 0
1040     struct timeval      tv;
1041 #endif    
1042     const struct entry  *eid;
1043     u_int16_t           ashort;
1044     struct stat         st;
1045
1046     ad->ad_magic = AD_MAGIC;
1047     ad->ad_version = ad->ad_flags;
1048     if (!ad->ad_version)
1049     ad->ad_version = AD_VERSION;
1050
1051     memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
1052     memset(ad->ad_data, 0, sizeof(ad->ad_data));
1053
1054 #if AD_VERSION == AD_VERSION2
1055     if (ad->ad_version == AD_VERSION2)
1056        eid = entry_order2;
1057     else
1058 #endif
1059        eid = entry_order1;
1060
1061     while (eid->id) {
1062         ad->ad_eid[eid->id].ade_off = eid->offset;
1063         ad->ad_eid[eid->id].ade_len = eid->len;
1064         eid++;
1065     }
1066             
1067     /* put something sane in the directory finderinfo */
1068     if ((adflags & ADFLAGS_DIR)) {
1069         /* set default view */
1070         ashort = htons(FINDERINFO_CLOSEDVIEW);
1071         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, 
1072                      &ashort, sizeof(ashort));
1073     } else {
1074         /* set default creator/type fields */
1075         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"TEXT", 4);
1076         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"UNIX", 4);
1077     }
1078
1079     /* make things invisible */
1080     if ((*path == '.') && strcmp(path, ".") && strcmp(path, "..")) {
1081         ashort = htons(ATTRBIT_INVISIBLE);
1082         ad_setattr(ad, ashort);
1083         ashort = htons(FINDERINFO_INVISIBLE);
1084         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,
1085                      &ashort, sizeof(ashort));
1086     }
1087
1088 #if 0
1089     if (gettimeofday(&tv, NULL) < 0) {
1090         return -1;
1091     } 
1092 #endif
1093     
1094     if (stat(path, &st) < 0) {
1095         return -1;
1096     }
1097             
1098     /* put something sane in the date fields */
1099     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
1100     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
1101     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
1102     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
1103     return 0;
1104 }
1105
1106 /* to do this with mmap, we need the hfs fs to understand how to mmap
1107    header files. */
1108 int ad_refresh(struct adouble *ad)
1109 {
1110
1111   if (ad->ad_hf.adf_fd < -1)
1112     return -1;
1113
1114   return ad_header_read(ad, NULL);
1115 }