]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Merge master
[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
26 /*!
27  * @file
28  * Part of Netatalk's AppleDouble implementatation
29  * @note We don't use inlines because a good compiler should be
30  *       able to optimize all the static funcs below.
31  * @sa include/atalk/adouble.h
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif /* HAVE_CONFIG_H */
37
38 #include <errno.h>
39 #include <sys/param.h>
40 #include <stdlib.h>
41 #include <string.h>
42
43 #include <atalk/logger.h>
44 #include <atalk/adouble.h>
45 #include <atalk/util.h>
46
47 #include "ad_private.h"
48
49 #ifndef MAX
50 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
51 #endif /* ! MAX */
52
53 /*
54  * AppleDouble entry default offsets.
55  * The layout looks like this:
56  *
57  * this is the v1 layout:
58  *     255         200         16          32          N
59  *  |  NAME |    COMMENT    | FILEI |    FINDERI    | RFORK |
60  *
61  * we need to change it to look like this:
62  *
63  * v2 layout:
64  * field       length (in bytes)
65  * NAME        255
66  * COMMENT     200
67  * FILEDATESI  16     replaces FILEI
68  * FINDERI     32
69  * DID          4     new
70  * AFPFILEI     4     new
71  * SHORTNAME   12     8.3 new
72  * RFORK        N
73  *
74  * so, all we need to do is replace FILEI with FILEDATESI, move RFORK,
75  * and add in the new fields.
76  */
77
78 #define ADEDOFF_MAGIC        (0)
79 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
80 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
81 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
82
83 /* initial lengths of some of the fields */
84 #define ADEDLEN_INIT     0
85
86 /* make sure we don't redefine ADEDOFF_FILEI */
87 #ifdef ADEDOFF_FILEI
88 #undef ADEDOFF_FILEI
89 #endif /* ADEDOFF_FILEI */
90
91 #define ADEDOFF_NAME_V1      (AD_HEADER_LEN + ADEID_NUM_V1*AD_ENTRY_LEN)
92 #define ADEDOFF_COMMENT_V1   (ADEDOFF_NAME_V1 + ADEDLEN_NAME)
93 #define ADEDOFF_FILEI        (ADEDOFF_COMMENT_V1 + ADEDLEN_COMMENT)
94 #define ADEDOFF_FINDERI_V1   (ADEDOFF_FILEI + ADEDLEN_FILEI)
95 #define ADEDOFF_RFORK_V1     (ADEDOFF_FINDERI_V1 + ADEDLEN_FINDERI)
96
97 /* i stick things in a slightly different order than their eid order in
98  * case i ever want to separate RootInfo behaviour from the rest of the
99  * stuff. */
100 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
101 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
102 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
103 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
104 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
105 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
106 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
107 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
108 #define ADEDOFF_PRIVDEV      (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
109 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
110 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
111 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
112 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
113
114 #define ADEDOFF_FINDERI_OSX  (AD_HEADER_LEN + ADEID_NUM_OSX*AD_ENTRY_LEN)
115 #define ADEDOFF_RFORK_OSX    (ADEDOFF_FINDERI_OSX + ADEDLEN_FINDERI)
116
117 /* we keep local copies of a bunch of stuff so that we can initialize things
118  * correctly. */
119
120 /* this is to prevent changing timezones from causing problems with
121    localtime volumes. the screw-up is 30 years. we use a delta of 5
122    years.  */
123 #define TIMEWARP_DELTA 157680000
124
125
126 struct entry {
127     uint32_t id, offset, len;
128 };
129
130 static uint32_t get_eid(struct adouble *ad, u_int32_t eid)
131 {
132     if (eid <= 15)
133         return eid;
134     if (eid == AD_DEV)
135         return ADEID_PRIVDEV;
136     if (eid == AD_INO)
137         return ADEID_PRIVINO;
138     if (eid == AD_SYN)
139         return ADEID_PRIVSYN;
140     if (eid == AD_ID)
141         return ADEID_PRIVID;
142
143     return 0;
144 }
145
146 #define DISK_EID(ad, a) get_eid(ad, a)
147
148 static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
149     {ADEID_NAME, ADEDOFF_NAME_V2, ADEDLEN_INIT},
150     {ADEID_COMMENT, ADEDOFF_COMMENT_V2, ADEDLEN_INIT},
151     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI, ADEDLEN_FILEDATESI},
152     {ADEID_FINDERI, ADEDOFF_FINDERI_V2, ADEDLEN_FINDERI},
153     {ADEID_DID, ADEDOFF_DID, ADEDLEN_DID},
154     {ADEID_AFPFILEI, ADEDOFF_AFPFILEI, ADEDLEN_AFPFILEI},
155     {ADEID_SHORTNAME, ADEDOFF_SHORTNAME, ADEDLEN_INIT},
156     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
157     {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV, ADEDLEN_INIT},
158     {ADEID_PRIVINO,     ADEDOFF_PRIVINO, ADEDLEN_INIT},
159     {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN, ADEDLEN_INIT},
160     {ADEID_PRIVID,     ADEDOFF_PRIVID, ADEDLEN_INIT},
161     {ADEID_RFORK, ADEDOFF_RFORK_V2, ADEDLEN_INIT},
162     {0, 0, 0}
163 };
164
165 /* OS X adouble finder info and resource fork only */
166 static const struct entry entry_order_osx[ADEID_NUM_OSX + 1] = {
167     {ADEID_FINDERI, ADEDOFF_FINDERI_OSX, ADEDLEN_FINDERI},
168     {ADEID_RFORK, ADEDOFF_RFORK_OSX, ADEDLEN_INIT},
169     {0, 0, 0}
170 };
171
172 /* Using Extended Attributes */
173 static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
174     {ADEID_FINDERI, ADEDOFF_FINDERI_OSX, ADEDLEN_FINDERI},
175     {ADEID_COMMENT, ADEDOFF_COMMENT_V2, ADEDLEN_INIT},
176     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI, ADEDLEN_FILEDATESI},
177     {ADEID_AFPFILEI, ADEDOFF_AFPFILEI, ADEDLEN_AFPFILEI},
178     {ADEID_PRIVID,     ADEDOFF_PRIVID, ADEDLEN_INIT},
179     {0, 0, 0}
180 };
181
182 /* update a version 2 adouble resource fork with our private entries */
183 static int ad_update(struct adouble *ad, const char *path)
184 {
185     struct stat st;
186     u_int16_t nentries = 0;
187     off_t     off, shiftdata=0;
188     const struct entry  *eid;
189     static off_t entry_len[ADEID_MAX];
190     static char  databuf[ADEID_MAX][256], *buf;
191     int fd;
192     int ret = -1;
193
194     /* check to see if we should convert this header. */
195     if (!path || ad->ad_flags != AD_VERSION2)
196         return 0;
197
198     LOG(log_maxdebug, logtype_default, "ad_update: checking whether '%s' needs an upgrade.", path);
199
200     if (!(ad->ad_md->adf_flags & O_RDWR)) {
201         /* we were unable to open the file read write the last time */
202         return 0;
203     }
204
205     if (ad->ad_eid[ADEID_RFORK].ade_off) {
206         shiftdata = ADEDOFF_RFORK_V2 -ad->ad_eid[ADEID_RFORK].ade_off;
207     }
208
209     memcpy(&nentries, ad->ad_data + ADEDOFF_NENTRIES, sizeof( nentries ));
210     nentries = ntohs( nentries );
211
212     if ( shiftdata == 0 && nentries == ADEID_NUM_V2)
213         return 0;
214
215     memset(entry_len, 0, sizeof(entry_len));
216     memset(databuf, 0, sizeof(databuf));
217
218     /* bail if we can't get a lock */
219     if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0)
220         goto bail_err;
221
222     fd = ad->ad_md->adf_fd;
223
224     if (fstat(fd, &st)) {
225         goto bail_lock;
226     }
227
228     if (st.st_size > 0x7fffffff) {
229         LOG(log_debug, logtype_default, "ad_update: file '%s' too big for update.", path);
230         errno = EIO;
231         goto bail_lock;
232     }
233
234     off = ad->ad_eid[ADEID_RFORK].ade_off;
235     if (off > st.st_size) {
236         LOG(log_error, logtype_default, "ad_update: invalid resource fork offset. (off: %u)", off);
237         errno = EIO;
238         goto bail_lock;
239     }
240
241     if (ad->ad_eid[ADEID_RFORK].ade_len > st.st_size - off) {
242         LOG(log_error, logtype_default, "ad_update: invalid resource fork length. (rfork len: %u)", ad->ad_eid[ADEID_RFORK].ade_len);
243         errno = EIO;
244         goto bail_lock;
245     }
246
247     if ((void *) (buf = (char *)
248                   mmap(NULL, st.st_size + shiftdata,
249                        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
250         MAP_FAILED) {
251         goto bail_lock;
252     }
253
254     /* last place for failure. */
255     if (sys_ftruncate(fd, st.st_size + shiftdata) < 0) {
256         munmap(buf, st.st_size + shiftdata);
257         goto bail_lock;
258     }
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
267     /* now, fix up our copy of the header */
268     memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
269
270     /* save the header entries */
271     eid = entry_order2;
272     while (eid->id) {
273         if( ad->ad_eid[eid->id].ade_off != 0) {
274             if ( eid->id > 2 && ad->ad_eid[eid->id].ade_len < 256)
275                 memcpy( databuf[eid->id], ad->ad_data +ad->ad_eid[eid->id].ade_off, ad->ad_eid[eid->id].ade_len);
276             entry_len[eid->id] = ad->ad_eid[eid->id].ade_len;
277         }
278         eid++;
279     }
280
281     memset(ad->ad_data + AD_HEADER_LEN, 0, AD_DATASZ - AD_HEADER_LEN);
282
283     /* copy the saved entries to the new header */
284     eid = entry_order2;
285     while (eid->id) {
286         if ( eid->id > 2 && entry_len[eid->id] > 0) {
287             memcpy(ad->ad_data+eid->offset, databuf[eid->id], entry_len[eid->id]);
288         }
289         ad->ad_eid[eid->id].ade_off = eid->offset;
290         ad->ad_eid[eid->id].ade_len = entry_len[eid->id];
291         eid++;
292     }
293
294     /* rebuild the header and cleanup */
295     LOG(log_debug, logtype_default, "updated AD2 header %s", path);
296     ad_flush(ad );
297     ret = 0;
298
299 bail_lock:
300     ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
301 bail_err:
302     return ret;
303 }
304
305 /* ------------------------------------------
306    FIXME work only if < 2GB
307 */
308 static int ad_convert(struct adouble *ad, const char *path)
309 {
310     struct stat st;
311     u_int16_t attr;
312     char *buf;
313     int fd, off;
314     int ret = -1;
315     /* use resource fork offset from file */
316     int shiftdata;
317     int toV2;
318     int toV1;
319
320     if (!path) {
321         return 0;
322     }
323
324     if (!(ad->ad_md->adf_flags & ( O_RDWR))) {
325         /* we were unable to open the file read write the last time */
326         return 0;
327     }
328
329     /* check to see if we should convert this header. */
330     toV2 = ad->ad_version == AD_VERSION1 && ad->ad_flags == AD_VERSION2;
331     toV1 = ad->ad_version == AD_VERSION2 && ad->ad_flags == AD_VERSION1;
332
333     if (!toV2 && !toV1)
334         return 0;
335
336     /* convert from v1 to v2. what does this mean?
337      *  1) change FILEI into FILEDATESI
338      *  2) create space for SHORTNAME, AFPFILEI, DID, and PRODOSI
339      *  3) move FILEI attributes into AFPFILEI
340      *  4) initialize ACCESS field of FILEDATESI.
341      *  5) move the resource fork
342      */
343
344     /* bail if we can't get a lock */
345     if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0)
346         goto bail_err;
347
348     /* we reuse fd from the resource fork */
349     fd = ad->ad_md->adf_fd;
350
351     if (ad->ad_eid[ADEID_RFORK].ade_off) {
352         shiftdata = ADEDOFF_RFORK_V2 -ad->ad_eid[ADEID_RFORK].ade_off;
353     }
354     else {
355         shiftdata = ADEDOFF_RFORK_V2 -ADEDOFF_RFORK_V1; /* 136 */
356     }
357
358     if (fstat(fd, &st)) {
359         goto bail_lock;
360     }
361
362     if (st.st_size > 0x7fffffff -shiftdata) {
363         LOG(log_debug, logtype_default, "ad_v1tov2: file too big.");
364         errno = EIO;
365         goto bail_lock;
366     }
367
368     off = ad->ad_eid[ADEID_RFORK].ade_off;
369
370     if (off > st.st_size) {
371         LOG(log_error, logtype_default, "ad_v1tov2: invalid resource fork offset. (off: %u)", off);
372         errno = EIO;
373         goto bail_lock;
374     }
375
376     if (ad->ad_eid[ADEID_RFORK].ade_len > st.st_size - off) {
377         LOG(log_error, logtype_default, "ad_v1tov2: invalid resource fork length. (rfork len: %u)", ad->ad_eid[ADEID_RFORK].ade_len);
378         errno = EIO;
379         goto bail_lock;
380     }
381
382     if ((void *) (buf = (char *)
383                   mmap(NULL, st.st_size + shiftdata,
384                        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
385         MAP_FAILED) {
386         goto bail_lock;
387     }
388
389     /* last place for failure. */
390
391     if (sys_ftruncate(fd, st.st_size + shiftdata) < 0) {
392         goto bail_lock;
393     }
394
395     /* move the RFORK. this assumes that the RFORK is at the end */
396     if (off) {
397         memmove(buf + ADEDOFF_RFORK_V2, buf + off, ad->ad_eid[ADEID_RFORK].ade_len);
398     }
399
400     munmap(buf, st.st_size + shiftdata);
401
402     /* now, fix up our copy of the header */
403     memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
404
405     /* replace FILEI with FILEDATESI */
406     ad_getattr(ad, &attr);
407     ad->ad_eid[ADEID_FILEDATESI].ade_off = ADEDOFF_FILEDATESI;
408     ad->ad_eid[ADEID_FILEDATESI].ade_len = ADEDLEN_FILEDATESI;
409     ad->ad_eid[ADEID_FILEI].ade_off = 0;
410     ad->ad_eid[ADEID_FILEI].ade_len = 0;
411
412     /* add in the new entries */
413     ad->ad_eid[ADEID_DID].ade_off = ADEDOFF_DID;
414     ad->ad_eid[ADEID_DID].ade_len = ADEDLEN_DID;
415     ad->ad_eid[ADEID_AFPFILEI].ade_off = ADEDOFF_AFPFILEI;
416     ad->ad_eid[ADEID_AFPFILEI].ade_len = ADEDLEN_AFPFILEI;
417     ad->ad_eid[ADEID_SHORTNAME].ade_off = ADEDOFF_SHORTNAME;
418     ad->ad_eid[ADEID_SHORTNAME].ade_len = ADEDLEN_INIT;
419     ad->ad_eid[ADEID_PRODOSFILEI].ade_off = ADEDOFF_PRODOSFILEI;
420     ad->ad_eid[ADEID_PRODOSFILEI].ade_len = ADEDLEN_PRODOSFILEI;
421
422     ad->ad_eid[ADEID_PRIVDEV].ade_off = ADEDOFF_PRIVDEV;
423     ad->ad_eid[ADEID_PRIVDEV].ade_len = ADEDLEN_INIT;
424     ad->ad_eid[ADEID_PRIVINO].ade_off = ADEDOFF_PRIVINO;
425     ad->ad_eid[ADEID_PRIVINO].ade_len = ADEDLEN_INIT;
426     ad->ad_eid[ADEID_PRIVSYN].ade_off = ADEDOFF_PRIVSYN;
427     ad->ad_eid[ADEID_PRIVSYN].ade_len = ADEDLEN_INIT;
428     ad->ad_eid[ADEID_PRIVID].ade_off  = ADEDOFF_PRIVID;
429     ad->ad_eid[ADEID_PRIVID].ade_len =  ADEDLEN_INIT;
430
431     /* shift the old entries (NAME, COMMENT, FINDERI, RFORK) */
432     ad->ad_eid[ADEID_NAME].ade_off = ADEDOFF_NAME_V2;
433     ad->ad_eid[ADEID_COMMENT].ade_off = ADEDOFF_COMMENT_V2;
434     ad->ad_eid[ADEID_FINDERI].ade_off = ADEDOFF_FINDERI_V2;
435     ad->ad_eid[ADEID_RFORK].ade_off = ADEDOFF_RFORK_V2;
436
437     /* switch to dest version */
438     ad->ad_version = (toV2)?AD_VERSION2:AD_VERSION1;
439
440     /* move our data buffer to make space for the new entries. */
441     memmove(ad->ad_data + ADEDOFF_NAME_V2, ad->ad_data + ADEDOFF_NAME_V1,
442             ADEDOFF_RFORK_V1 - ADEDOFF_NAME_V1);
443
444     /* now, fill in the space with appropriate stuff. we're
445        operating as a v2 file now. */
446     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
447     memset(ad_entry(ad, ADEID_DID), 0, ADEDLEN_DID);
448     memset(ad_entry(ad, ADEID_AFPFILEI), 0, ADEDLEN_AFPFILEI);
449     ad_setattr(ad, attr);
450     memset(ad_entry(ad, ADEID_SHORTNAME), 0, ADEDLEN_SHORTNAME);
451     memset(ad_entry(ad, ADEID_PRODOSFILEI), 0, ADEDLEN_PRODOSFILEI);
452
453     /* rebuild the header and cleanup */
454     ad_flush(ad );
455     ret = 0;
456
457 bail_lock:
458     ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
459 bail_err:
460     return ret;
461 }
462
463 /* -------------------------------------
464    read in the entries
465 */
466 static void parse_entries(struct adouble *ad, char *buf,
467                           u_int16_t nentries)
468 {
469     u_int32_t   eid, len, off;
470     int         warning = 0;
471
472     /* now, read in the entry bits */
473     for (; nentries > 0; nentries-- ) {
474         memcpy(&eid, buf, sizeof( eid ));
475         eid = DISK_EID(ad, ntohl( eid ));
476         buf += sizeof( eid );
477         memcpy(&off, buf, sizeof( off ));
478         off = ntohl( off );
479         buf += sizeof( off );
480         memcpy(&len, buf, sizeof( len ));
481         len = ntohl( len );
482         buf += sizeof( len );
483
484         if (eid && eid < ADEID_MAX && off < sizeof(ad->ad_data) &&
485             (off +len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
486             ad->ad_eid[ eid ].ade_off = off;
487             ad->ad_eid[ eid ].ade_len = len;
488         } else if (!warning) {
489             warning = 1;
490             LOG(log_debug, logtype_default, "ad_refresh: nentries %hd  eid %d",
491                 nentries, eid );
492         }
493     }
494 }
495
496 /***********************************************************************
497  * adouble v2 scheme funcs
498  ***********************************************************************/
499
500 /* this reads enough of the header so that we can figure out all of
501  * the entry lengths and offsets. once that's done, we just read/mmap
502  * the rest of the header in.
503  *
504  * NOTE: we're assuming that the resource fork is kept at the end of
505  *       the file. also, mmapping won't work for the hfs fs until it
506  *       understands how to mmap header files. */
507 static int ad_header_read(struct adouble *ad, struct stat *hst)
508 {
509     char                *buf = ad->ad_data;
510     u_int16_t           nentries;
511     int                 len;
512     ssize_t             header_len;
513     static int          warning = 0;
514     struct stat         st;
515
516     /* read the header */
517     if ((header_len = adf_pread( ad->ad_md, buf, sizeof(ad->ad_data), 0)) < 0) {
518         return -1;
519     }
520     if (header_len < AD_HEADER_LEN) {
521         errno = EIO;
522         return -1;
523     }
524
525     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
526     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
527
528     /* tag broken v1 headers. just assume they're all right.
529      * we detect two cases: null magic/version
530      *                      byte swapped magic/version
531      * XXX: in the future, you'll need the v1compat flag.
532      * (ad->ad_flags & ADFLAGS_V1COMPAT) */
533     if (!ad->ad_magic && !ad->ad_version) {
534         if (!warning) {
535             LOG(log_debug, logtype_default, "notice: fixing up null v1 magic/version.");
536             warning++;
537         }
538         ad->ad_magic = AD_MAGIC;
539         ad->ad_version = AD_VERSION1;
540
541     } else if (ad->ad_magic == AD_MAGIC && ad->ad_version == AD_VERSION1) {
542         if (!warning) {
543             LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
544             warning++;
545         }
546
547     } else {
548         ad->ad_magic = ntohl( ad->ad_magic );
549         ad->ad_version = ntohl( ad->ad_version );
550     }
551
552     if ((ad->ad_magic != AD_MAGIC) ||
553         ((ad->ad_version != AD_VERSION1) && (ad->ad_version != AD_VERSION2))) {
554         LOG(log_debug, logtype_default, "ad_open: can't parse AppleDouble header.");
555         errno = EIO;
556         return -1;
557     }
558
559     memcpy(ad->ad_filler, buf + ADEDOFF_FILLER, sizeof( ad->ad_filler ));
560     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
561     nentries = ntohs( nentries );
562
563     /* read in all the entry headers. if we have more than the
564      * maximum, just hope that the rfork is specified early on. */
565     len = nentries*AD_ENTRY_LEN;
566
567     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
568         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
569
570     buf += AD_HEADER_LEN;
571     if (len > header_len - AD_HEADER_LEN) {
572         LOG(log_debug, logtype_default, "ad_header_read: can't read entry info.");
573         errno = EIO;
574         return -1;
575     }
576
577     /* figure out all of the entry offsets and lengths. if we aren't
578      * able to read a resource fork entry, bail. */
579     nentries = len / AD_ENTRY_LEN;
580     parse_entries(ad, buf, nentries);
581     if (!ad_getentryoff(ad, ADEID_RFORK)
582         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
583         ) {
584         LOG(log_debug, logtype_default, "ad_header_read: problem with rfork entry offset.");
585         errno = EIO;
586         return -1;
587     }
588
589     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
590         LOG(log_debug, logtype_default, "ad_header_read: can't read in entries.");
591         errno = EIO;
592         return -1;
593     }
594
595     if (hst == NULL) {
596         hst = &st;
597         if (fstat(ad->ad_md->adf_fd, &st) < 0) {
598             return 1; /* fail silently */
599         }
600     }
601     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
602
603     /* fix up broken dates */
604     if (ad->ad_version == AD_VERSION1) {
605         u_int32_t aint;
606
607         /* check to see if the ad date is wrong. just see if we have
608          * a modification date in the future. */
609         if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
610             (aint > TIMEWARP_DELTA + hst->st_mtime)) {
611             ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
612             ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
613             ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
614             ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
615             ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
616         }
617     }
618
619     return 0;
620 }
621
622 /*
623  * Put the .AppleDouble where it needs to be:
624  *
625  *      /   a/.AppleDouble/b
626  *  a/b
627  *      \   b/.AppleDouble/.Parent
628  *
629  * FIXME: should do something for pathname > MAXPATHLEN
630  */
631 char *ad_path( const char *path, int adflags)
632 {
633     static char pathbuf[ MAXPATHLEN + 1];
634     const char *slash;
635     size_t  l ;
636
637     if ( adflags & ADFLAGS_DIR ) {
638         l = strlcpy( pathbuf, path, sizeof(pathbuf));
639
640         if ( l && l < MAXPATHLEN) {
641             pathbuf[l++] = '/';
642         }
643         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
644     } else {
645         if (NULL != ( slash = strrchr( path, '/' )) ) {
646             slash++;
647             l = slash - path;
648             /* XXX we must return NULL here and test in the caller */
649             if (l > MAXPATHLEN)
650                 l = MAXPATHLEN;
651             memcpy( pathbuf, path, l);
652         } else {
653             l = 0;
654             slash = path;
655         }
656         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
657         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
658     }
659
660     return( pathbuf );
661 }
662
663 static int ad_mkrf(char *path)
664 {
665     char *slash;
666     /*
667      * Probably .AppleDouble doesn't exist, try to mkdir it.
668      */
669     if (NULL == ( slash = strrchr( path, '/' )) ) {
670         return -1;
671     }
672     *slash = '\0';
673     errno = 0;
674     if ( ad_mkdir( path, 0777 ) < 0 ) {
675         return -1;
676     }
677     *slash = '/';
678     return 0;
679 }
680
681
682 /***********************************************************************
683  * OS X adouble scheme funcs
684  ***********************************************************************/
685
686 /*
687  * Put the resource fork where it needs to be: ._name
688  */
689 char *ad_path_osx(const char *path, int adflags _U_)
690 {
691     static char pathbuf[ MAXPATHLEN + 1];
692     char    c, *slash, buf[MAXPATHLEN + 1];
693
694     if (!strcmp(path,".")) {
695         /* fixme */
696         getcwd(buf, MAXPATHLEN);
697     }
698     else {
699         strlcpy(buf, path, MAXPATHLEN +1);
700     }
701     if (NULL != ( slash = strrchr( buf, '/' )) ) {
702         c = *++slash;
703         *slash = '\0';
704         strlcpy( pathbuf, buf, MAXPATHLEN +1);
705         *slash = c;
706     } else {
707         pathbuf[ 0 ] = '\0';
708         slash = buf;
709     }
710     strlcat( pathbuf, "._", MAXPATHLEN  +1);
711     strlcat( pathbuf, slash, MAXPATHLEN +1);
712     return pathbuf;
713 }
714
715 /* -------------------- */
716 static int ad_mkrf_osx(char *path _U_)
717 {
718     return 0;
719 }
720
721 /* -------------------------
722  * Support inherited protection modes for AppleDouble files.  The supplied
723  * mode is ANDed with the parent directory's mask value in lieu of "umask",
724  * and that value is returned.
725  */
726
727 #define DEFMASK 07700   /* be conservative */
728
729 char *ad_dir(const char *path)
730 {
731     static char     modebuf[ MAXPATHLEN + 1];
732     char        *slash;
733     /*
734      * For a path with directories in it, remove the final component
735      * (path or subdirectory name) to get the name we want to stat.
736      * For a path which is just a filename, use "." instead.
737      */
738     slash = strrchr( path, '/' );
739     if (slash) {
740         size_t len;
741
742         len = slash - path;
743         if (len >= MAXPATHLEN) {
744             errno = ENAMETOOLONG;
745             return NULL;  /* can't do it */
746         }
747         memcpy( modebuf, path, len );
748         modebuf[len] = '\0';
749         /* is last char a '/' ? */
750         if (slash[1] == 0) {
751             slash = modebuf+ len;
752             /* remove them */
753             while (modebuf < slash && slash[-1] == '/') {
754                 --slash;
755             }
756             if (modebuf == slash) {
757                 goto use_cur;
758             }
759             *slash = '\0';
760             while (modebuf < slash && *slash != '/') {
761                 --slash;
762             }
763             if (modebuf == slash) {
764                 goto use_cur;
765             }
766             *slash = '\0';      /* remove pathname component */
767         }
768         return modebuf;
769     }
770 use_cur:
771     modebuf[0] = '.';   /* use current directory */
772     modebuf[1] = '\0';
773     return modebuf;
774 }
775
776 /* ---------------- */
777 static uid_t default_uid = -1;
778
779 int ad_setfuid(const uid_t id)
780 {
781     default_uid = id;
782     return 0;
783 }
784
785 /* ---------------- */
786 uid_t ad_getfuid(void)
787 {
788     return default_uid;
789 }
790
791 /* ----------------
792    return inode of path parent directory
793 */
794 int ad_stat(const char *path, struct stat *stbuf)
795 {
796     char                *p;
797
798     p = ad_dir(path);
799     if (!p) {
800         return -1;
801     }
802 //FIXME!
803     return lstat( p, stbuf );
804 }
805
806 /* ----------------
807    if we are root change path user/ group
808    It can be a native function for BSD cf. FAQ.Q10
809    path:  pathname to chown
810    stbuf: parent directory inode
811
812    use fstat and fchown or lchown with linux?
813 */
814 #define EMULATE_SUIDDIR
815
816 static int ad_chown(const char *path, struct stat *stbuf)
817 {
818     int ret = 0;
819 #ifdef EMULATE_SUIDDIR
820     uid_t id;
821
822     if (default_uid != (uid_t)-1) {
823         /* we are root (admin) */
824         id = (default_uid)?default_uid:stbuf->st_uid;
825         ret = lchown( path, id, stbuf->st_gid );
826     }
827 #endif
828     return ret;
829 }
830
831 /* ----------------
832    return access right and inode of path parent directory
833 */
834 static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
835 {
836     if (*mode == 0) {
837         return -1;
838     }
839     if (ad_stat(path, stbuf) != 0) {
840         *mode &= DEFMASK;
841         return -1;
842     }
843     *mode &= stbuf->st_mode;
844     return 0;
845 }
846
847 /* ----------------
848    return access right of path parent directory
849 */
850 int
851 ad_mode( const char *path, int mode)
852 {
853     struct stat     stbuf;
854     ad_mode_st(path, &mode, &stbuf);
855     return mode;
856 }
857
858 /*
859  * Use mkdir() with mode bits taken from ad_mode().
860  */
861 int
862 ad_mkdir( const char *path, int mode)
863 {
864     int ret;
865     int st_invalid;
866     struct stat stbuf;
867
868     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
869         path, mode, getcwdpath());
870
871     st_invalid = ad_mode_st(path, &mode, &stbuf);
872     ret = mkdir( path, mode );
873     if (ret || st_invalid)
874         return ret;
875     ad_chown(path, &stbuf);
876
877     return ret;
878 }
879
880 /* ----------------- */
881 static int ad_error(struct adouble *ad, int adflags)
882 {
883     int err = errno;
884     if ((adflags & ADFLAGS_NOHF)) {
885         /* FIXME double check : set header offset ?*/
886         return 0;
887     }
888     if ((adflags & ADFLAGS_DF)) {
889         ad_close( ad, ADFLAGS_DF );
890         err = errno;
891     }
892     return -1 ;
893 }
894
895 static int new_rfork(const char *path, struct adouble *ad, int adflags);
896
897 #ifdef  HAVE_PREAD
898 #define AD_SET(a)
899 #else
900 #define AD_SET(a) a = 0
901 #endif
902
903 /* --------------------------- */
904 static int ad_check_size(struct adouble *ad _U_, struct stat *st)
905 {
906     if (st->st_size > 0 && st->st_size < AD_DATASZ1)
907         return 1;
908     return 0;
909 }
910
911 /* --------------------------- */
912 static int ad_check_size_sfm(struct adouble *ad _U_, struct stat *st)
913 {
914     if (st->st_size > 0 && st->st_size < AD_SFM_LEN)
915         return 1;
916     return 0;
917 }
918
919 /* --------------------------- */
920 static int ad_header_upgrade(struct adouble *ad, char *name)
921 {
922     int ret;
923     if ( (ret = ad_convert(ad, name)) < 0 || (ret = ad_update(ad, name) < 0)) {
924         return ret;
925     }
926     return 0;
927 }
928
929 /* --------------------------- */
930 static int ad_header_upgrade_none(struct adouble *ad _U_, char *name _U_)
931 {
932     return 0;
933 }
934
935 /* --------------------------- */
936 static struct adouble_fops ad_osx = {
937     &ad_path_osx,
938     &ad_mkrf_osx,
939     &ad_rebuild_adouble_header,
940     &ad_check_size,
941     &ad_header_read,
942     &ad_header_upgrade,
943 };
944
945 static struct adouble_fops ad_adouble = {
946     &ad_path,
947     &ad_mkrf,
948     &ad_rebuild_adouble_header,
949     &ad_check_size,
950     &ad_header_read,
951     &ad_header_upgrade,
952 };
953
954 static struct adouble_fops ad_adouble_ea = {
955     &ad_path,
956     &ad_mkrf,
957     &ad_rebuild_adouble_header,
958     &ad_check_size,
959     &ad_header_read,
960     &ad_header_upgrade,
961 };
962
963 void ad_init(struct adouble *ad, int flags, int options)
964 {
965     ad->ad_inited = 0;
966     ad->ad_flags = flags;
967     if (flags == AD_VERSION2_OSX) {
968         ad->ad_ops = &ad_osx;
969         ad->ad_md = &ad->ad_resource_fork;
970     }
971     else if (flags == AD_VERSION2) {
972         ad->ad_ops = &ad_adouble;
973         ad->ad_md = &ad->ad_resource_fork;
974     }
975     else {
976         ad->ad_ops = &ad_adouble_ea;
977         ad->ad_md = &ad->ad_metadata_fork;
978     }
979     ad->ad_options = options;
980
981     ad_data_fileno(ad) = -1;
982     ad_reso_fileno(ad) = -1;
983     ad_meta_fileno(ad) = -1;
984     /* following can be read even if there's no meda data. */
985     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
986     ad->ad_rlen = 0;
987 }
988
989 /*!
990  * Open data-, metadata(header)- or ressource fork
991  *
992  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
993  * @code
994  *      struct adoube ad;
995  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
996  * @endcode
997  *
998  * @param path    Path to file or directory
999  * @param adflags ADFLAGS_DF: open data file/fork\n
1000  *                ADFLAGS_HF: open header (metadata) file\n
1001  *                ADFLAGS_RF: open ressource fork *** FIXME: not used ?! *** \n
1002  *                ADFLAGS_CREATE: indicate creation\n
1003  *                ADFLAGS_NOHF: it's not an error if header file couldn't be created\n
1004  *                ADFLAGS_DIR: if path is a directory you MUST or ADFLAGS_DIR to adflags\n
1005  *                ADFLAGS_NOADOUBLE: dont create adouble files if not necessary\n
1006  *                ADFLAGS_RDONLY: open read only\n
1007  *                ADFLAGS_OPENFORKS: check for open forks from other processes\n
1008  *                ADFLAGS_MD: alias for ADFLAGS_HF\n
1009  *                ADFLAGS_V1COMPAT: obsolete
1010  * @param oflags  flags passed through to open syscall: \n
1011  *                O_RDONLY: *** FIXME *** \n
1012  *                O_RDWR: *** FIXME *** \n
1013  *                O_CREAT: create fork\n
1014  *                O_EXCL: fail if exists with O_CREAT
1015  * @param mode    passed to open with O_CREAT
1016  * @param ad      pointer to struct adouble
1017  *
1018  * @returns 0 on success
1019  *
1020  * @note It's not possible to open the header file O_RDONLY -- the read
1021  *       will fail and return an error. this refcounts things now.\n
1022  *       metadata(ressource)-fork only gets created with O_CREAT.
1023  */
1024 int ad_open( const char *path, int adflags, int oflags, int mode, struct adouble  *ad)
1025 {
1026     struct stat         st_dir;
1027     struct stat         st_meta;
1028     struct stat         *pst = NULL;
1029     char        *ad_p;
1030     int         hoflags, admode;
1031     int                 st_invalid = -1;
1032     int                 open_df = 0;
1033
1034     if (ad->ad_inited != AD_INITED) {
1035         ad->ad_inited = AD_INITED;
1036         ad->ad_refcount = 1;
1037         ad->ad_open_forks = 0;
1038         ad->ad_adflags = adflags;
1039         ad->ad_resource_fork.adf_refcount = 0;
1040         ad->ad_data_fork.adf_refcount = 0;
1041         ad->ad_data_fork.adf_syml=0;
1042     }
1043     else {
1044         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1045         /* XXX not true if we have a meta data fork ? */
1046         if ((ad->ad_resource_fork.adf_refcount > ad->ad_data_fork.adf_refcount))
1047             ad->ad_open_forks |= ATTRBIT_ROPEN;
1048     }
1049
1050     if ((adflags & ADFLAGS_DF)) {
1051         if (ad_data_fileno(ad) == -1) {
1052             hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
1053             admode = mode;
1054             if ((oflags & O_CREAT)) {
1055                 st_invalid = ad_mode_st(path, &admode, &st_dir);
1056                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1057                     admode = mode;
1058                 }
1059             }
1060                 
1061             ad->ad_data_fork.adf_fd =open( path, hoflags | O_NOFOLLOW, admode );
1062             
1063             if (ad->ad_data_fork.adf_fd == -1) {
1064                 if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
1065                     hoflags = oflags;
1066                     ad->ad_data_fork.adf_fd = open( path, hoflags | O_NOFOLLOW, admode );
1067                 }
1068                 if (ad->ad_data_fork.adf_fd == -1 && errno == OPEN_NOFOLLOW_ERRNO) {
1069                     int lsz;
1070
1071                     ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
1072                     lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN);
1073                     if (lsz <= 0) {
1074                         free(ad->ad_data_fork.adf_syml);
1075                         return -1;
1076                     }
1077                     ad->ad_data_fork.adf_syml[lsz] = 0;
1078                     ad->ad_data_fork.adf_fd = -2; /* -2 means its a symlink */
1079                 }
1080             }
1081
1082             if ( ad->ad_data_fork.adf_fd == -1 )
1083                 return -1;
1084
1085             AD_SET(ad->ad_data_fork.adf_off);
1086             ad->ad_data_fork.adf_flags = hoflags;
1087             if (!st_invalid) {
1088                 /* just created, set owner if admin (root) */
1089                 ad_chown(path, &st_dir);
1090             }
1091             adf_lock_init(&ad->ad_data_fork);
1092         }
1093         else {
1094             /* the file is already open... but */
1095             if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
1096                 !(ad->ad_data_fork.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
1097             {
1098                 errno = EACCES;
1099                 return -1;
1100             }
1101             /* FIXME
1102              * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
1103              * already open. Should we check for it? ie
1104              * O_EXCL --> error
1105              * O_TRUNC --> truncate the fork.
1106              * idem for ressource fork.
1107              */
1108         }
1109         open_df = ADFLAGS_DF;
1110         ad->ad_data_fork.adf_refcount++;
1111     }
1112
1113     if (!(adflags & ADFLAGS_HF))
1114         return 0;
1115
1116     /* ****************************************** */
1117
1118     if (ad_meta_fileno(ad) != -1) { /* the file is already open */
1119         if ((oflags & ( O_RDWR | O_WRONLY)) &&
1120             !(ad->ad_md->adf_flags & ( O_RDWR | O_WRONLY))) {
1121             if (open_df) {
1122                 /* don't call with ADFLAGS_HF because we didn't open ressource fork */
1123                 ad_close( ad, open_df );
1124             }
1125             errno = EACCES;
1126             return -1;
1127         }
1128         ad_refresh(ad);
1129         /* it's not new anymore */
1130         ad->ad_md->adf_flags &= ~( O_TRUNC | O_CREAT );
1131         ad->ad_md->adf_refcount++;
1132         goto sfm;
1133     }
1134
1135     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
1136     ad->ad_rlen = 0;
1137     ad_p = ad->ad_ops->ad_path( path, adflags );
1138
1139     hoflags = oflags & ~(O_CREAT | O_EXCL);
1140     if (!(adflags & ADFLAGS_RDONLY)) {
1141         hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
1142     }
1143     ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
1144     if (ad->ad_md->adf_fd < 0 ) {
1145         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
1146             hoflags = oflags & ~(O_CREAT | O_EXCL);
1147             ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
1148         }
1149     }
1150
1151     if ( ad->ad_md->adf_fd < 0 ) {
1152         if (errno == ENOENT && (oflags & O_CREAT) ) {
1153             /*
1154              * We're expecting to create a new adouble header file,
1155              * here.
1156              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
1157              */
1158             LOG(log_debug, logtype_default, "ad_open(\"%s\"): {cwd: \"%s\"} creating adouble file",
1159                 ad_p, getcwdpath());
1160             admode = mode;
1161             errno = 0;
1162             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1163             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1164                 admode = mode;
1165             }
1166             admode = ad_hf_mode(admode);
1167             if ((errno == ENOENT) && (ad->ad_flags != AD_VERSION2_OSX)) {
1168                 if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
1169                     return ad_error(ad, adflags);
1170                 }
1171                 admode = mode;
1172                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1173                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1174                     admode = mode;
1175                 }
1176                 admode = ad_hf_mode(admode);
1177             }
1178             /* retry with O_CREAT */
1179             ad->ad_md->adf_fd = open( ad_p, oflags,admode );
1180             if ( ad->ad_md->adf_fd < 0 ) {
1181                 return ad_error(ad, adflags);
1182             }
1183             ad->ad_md->adf_flags = oflags;
1184             /* just created, set owner if admin owner (root) */
1185             if (!st_invalid) {
1186                 ad_chown(ad_p, &st_dir);
1187             }
1188         }
1189         else {
1190             return ad_error(ad, adflags);
1191         }
1192     } else {
1193         ad->ad_md->adf_flags = hoflags;
1194         if (fstat(ad->ad_md->adf_fd, &st_meta) == 0 && st_meta.st_size == 0) {
1195             /* for 0 length files, treat them as new. */
1196             ad->ad_md->adf_flags |= O_TRUNC;
1197         } 
1198         else {
1199             /* we have valid data in st_meta stat structure, reused it
1200                in ad_header_read
1201             */
1202             pst = &st_meta;
1203         }
1204     }
1205     AD_SET(ad->ad_md->adf_off);
1206
1207     ad->ad_md->adf_refcount = 1;
1208     adf_lock_init(ad->ad_md);
1209     if ((ad->ad_md->adf_flags & ( O_TRUNC | O_CREAT ))) {
1210         /*
1211          * This is a new adouble header file. Initialize the structure,
1212          * instead of reading it.
1213          */
1214         if (new_rfork(path, ad, adflags) < 0) {
1215             int err = errno;
1216             /* the file is already deleted, perm, whatever, so return an error*/
1217             ad_close(ad, adflags);
1218             errno = err;
1219             return -1;
1220         }
1221         ad_flush(ad);
1222     } else {
1223         /* Read the adouble header in and parse it.*/
1224         if (ad->ad_ops->ad_header_read( ad , pst) < 0
1225             || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0)
1226         {
1227             int err = errno;
1228
1229             ad_close( ad, adflags );
1230             errno = err;
1231             return -1;
1232         }
1233     }
1234
1235     /* ****************************************** */
1236     /* open the resource fork if SFM */
1237 sfm:
1238     if (ad->ad_flags != AD_VERSION1_SFM) {
1239         return 0;
1240     }
1241
1242     if ((adflags & ADFLAGS_DIR)) {
1243         /* no resource fork for directories / volumes XXX it's false! */
1244         return 0;
1245     }
1246
1247     /* untrue yet but ad_close will decremente it*/
1248     ad->ad_resource_fork.adf_refcount++;
1249
1250     if (ad_reso_fileno(ad) != -1) { /* the file is already open */
1251         if ((oflags & ( O_RDWR | O_WRONLY)) &&
1252             !(ad->ad_resource_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
1253
1254             ad_close( ad, open_df | ADFLAGS_HF);
1255             errno = EACCES;
1256             return -1;
1257         }
1258         return 0;
1259     }
1260
1261     ad_p = ad->ad_ops->ad_path( path, ADFLAGS_RF );
1262
1263     admode = mode;
1264     st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1265
1266     if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1267         admode = mode;
1268     }
1269
1270     hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
1271     ad->ad_resource_fork.adf_fd = open( ad_p, hoflags, admode );
1272
1273     if (ad->ad_resource_fork.adf_fd < 0 ) {
1274         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
1275             hoflags = oflags;
1276             ad->ad_resource_fork.adf_fd =open( ad_p, hoflags, admode );
1277         }
1278     }
1279
1280     if ( ad->ad_resource_fork.adf_fd < 0) {
1281         int err = errno;
1282
1283         ad_close( ad, adflags );
1284         errno = err;
1285         return -1;
1286     }
1287     adf_lock_init(&ad->ad_resource_fork);
1288     AD_SET(ad->ad_resource_fork.adf_off);
1289     ad->ad_resource_fork.adf_flags = hoflags;
1290     if ((oflags & O_CREAT) && !st_invalid) {
1291         /* just created, set owner if admin (root) */
1292         ad_chown(ad_p, &st_dir);
1293     }
1294     else if (!fstat(ad->ad_resource_fork.adf_fd, &st_meta)) {
1295         ad->ad_rlen = st_meta.st_size;
1296     }
1297     return 0 ;
1298 }
1299
1300 /*!
1301  * @brief open metadata, possibly as root
1302  *
1303  * Return only metadata but try very hard ie at first try as user, then try as root.
1304  *
1305  * @param name  name of file/dir
1306  * @param flags ADFLAGS_DIR: name is a directory \n
1307  *              ADFLAGS_CREATE: force creation of header file, but only as user, not as root\n
1308  *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
1309  *
1310  * @param adp   pointer to struct adouble
1311  *
1312  * @note caller MUST pass ADFLAGS_DIR for directories. Whether ADFLAGS_CREATE really creates
1313  *       a adouble file depends on various other volume options, eg. ADVOL_CACHE
1314  */
1315 int ad_metadata(const char *name, int flags, struct adouble *adp)
1316 {
1317     uid_t uid;
1318     int   ret, err, dir;
1319     int   create = O_RDONLY;
1320
1321     dir = flags & ADFLAGS_DIR;
1322
1323     /* Check if we shall call ad_open with O_CREAT */
1324     if ( (adp->ad_options & ADVOL_CACHE)
1325          && ! (adp->ad_options & ADVOL_NOADOUBLE)
1326          && (flags & ADFLAGS_CREATE) ) {
1327         create = O_CREAT | O_RDWR;
1328     }
1329     if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
1330         uid = geteuid();
1331         if (seteuid(0)) {
1332             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1333             errno = EACCES;
1334             return -1;
1335         }
1336         /* we are root open read only */
1337         ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
1338         err = errno;
1339         if ( seteuid(uid) < 0) {
1340             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1341             exit(EXITERR_SYS);
1342         }
1343         errno = err;
1344     }
1345
1346     if (!ret && (ADFLAGS_OPENFORKS & flags)) {
1347         /*
1348           we need to check if the file is open by another process.
1349           it's slow so we only do it if we have to:
1350           - it's requested.
1351           - we don't already have the answer!
1352         */
1353         adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
1354     }
1355     return ret;
1356 }
1357
1358 /*
1359  * @brief openat like wrapper for ad_metadata
1360  */
1361 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1362 {
1363     int ret = 0;
1364     int cwdfd = -1;
1365
1366     if (dirfd != -1) {
1367         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1368             ret = -1;
1369             goto exit;
1370         }
1371     }
1372
1373     if (ad_metadata(name, flags, adp) < 0) {
1374         ret = -1;
1375         goto exit;
1376     }
1377
1378     if (dirfd != -1) {
1379         if (fchdir(cwdfd) != 0) {
1380             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1381             exit(EXITERR_SYS);
1382         }
1383     }
1384
1385 exit:
1386     if (cwdfd != -1)
1387         close(cwdfd);
1388
1389     return ret;
1390
1391 }
1392
1393 /* ----------------------------------- */
1394 static int new_rfork(const char *path, struct adouble *ad, int adflags)
1395 {
1396     const struct entry  *eid;
1397     u_int16_t           ashort;
1398     struct stat         st;
1399
1400     ad->ad_magic = AD_MAGIC;
1401     ad->ad_version = ad->ad_flags & 0x0f0000;
1402     if (!ad->ad_version) {
1403         ad->ad_version = AD_VERSION;
1404     }
1405
1406     memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
1407     memset(ad->ad_data, 0, sizeof(ad->ad_data));
1408
1409     if (ad->ad_flags == AD_VERSION2)
1410         eid = entry_order2;
1411     else if (ad->ad_flags == AD_VERSION2_OSX)
1412         eid = entry_order_osx;
1413     else {
1414         eid = entry_order_ea;
1415     }
1416
1417     while (eid->id) {
1418         ad->ad_eid[eid->id].ade_off = eid->offset;
1419         ad->ad_eid[eid->id].ade_len = eid->len;
1420         eid++;
1421     }
1422
1423     /* put something sane in the directory finderinfo */
1424     if ((adflags & ADFLAGS_DIR)) {
1425         /* set default view */
1426         ashort = htons(FINDERINFO_CLOSEDVIEW);
1427         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF,
1428                &ashort, sizeof(ashort));
1429     } else {
1430         /* set default creator/type fields */
1431         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
1432         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
1433     }
1434
1435     /* make things invisible */
1436     if ((ad->ad_options & ADVOL_INVDOTS) && !(adflags & ADFLAGS_CREATE) &&
1437         (*path == '.') && strcmp(path, ".") && strcmp(path, ".."))
1438     {
1439         ashort = htons(ATTRBIT_INVISIBLE);
1440         ad_setattr(ad, ashort);
1441         ashort = htons(FINDERINFO_INVISIBLE);
1442         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
1443     }
1444
1445     if (lstat(path, &st) < 0) {
1446         return -1;
1447     }
1448
1449     /* put something sane in the date fields */
1450     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
1451     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
1452     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
1453     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
1454     return 0;
1455 }
1456
1457 /* to do this with mmap, we need the hfs fs to understand how to mmap
1458    header files. */
1459 int ad_refresh(struct adouble *ad)
1460 {
1461
1462     if (ad_meta_fileno(ad) < 0)
1463         return -1;
1464
1465     return ad->ad_ops->ad_header_read(ad, NULL);
1466 }
1467
1468 int ad_openat(int dirfd,  /* dir fd openat like */
1469               const char *path,
1470               int adflags,
1471               int oflags,
1472               int mode,
1473               struct adouble  *ad)
1474 {
1475     int ret = 0;
1476     int cwdfd = -1;
1477
1478     if (dirfd != -1) {
1479         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1480             ret = -1;
1481             goto exit;
1482         }
1483     }
1484
1485     if (ad_open(path, adflags, oflags, mode, ad) < 0) {
1486         ret = -1;
1487         goto exit;
1488     }
1489
1490     if (dirfd != -1) {
1491         if (fchdir(cwdfd) != 0) {
1492             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1493             exit(EXITERR_SYS);
1494         }
1495     }
1496
1497 exit:
1498     if (cwdfd != -1)
1499         close(cwdfd);
1500
1501     return ret;
1502 }