]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
ea221ff4ec62964f827a8e2e8771a945d18c8b27
[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  * Copyright (c) 2010 Frank Lahm
5  *
6  * All Rights Reserved.
7  *
8  * Permission to use, copy, modify, and distribute this software and
9  * its documentation for any purpose and without fee is hereby granted,
10  * provided that the above copyright notice appears in all copies and
11  * that both that copyright notice and this permission notice appear
12  * in supporting documentation, and that the name of The University
13  * of Michigan not be used in advertising or publicity pertaining to
14  * distribution of the software without specific, written prior
15  * permission. This software is supplied as is without expressed or
16  * implied warranties of any kind.
17  *
18  *  Research Systems Unix Group
19  *  The University of Michigan
20  *  c/o Mike Clark
21  *  535 W. William Street
22  *  Ann Arbor, Michigan
23  *  +1-313-763-0525
24  *  netatalk@itd.umich.edu
25  *
26  */
27
28 /*!
29  * @file
30  * Part of Netatalk's AppleDouble implementatation
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 #include <stdarg.h>
43 #include <arpa/inet.h>
44
45 #include <atalk/logger.h>
46 #include <atalk/adouble.h>
47 #include <atalk/util.h>
48 #include <atalk/unix.h>
49 #include <atalk/ea.h>
50 #include <atalk/bstrlib.h>
51 #include <atalk/bstradd.h>
52 #include <atalk/compat.h>
53 #include <atalk/errchk.h>
54 #include <atalk/volume.h>
55
56 #include "ad_lock.h"
57
58 #define ADEDOFF_MAGIC        (0)
59 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
60 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
61 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
62
63 /* initial lengths of some of the fields */
64 #define ADEDLEN_INIT     0
65
66 /* i stick things in a slightly different order than their eid order in
67  * case i ever want to separate RootInfo behaviour from the rest of the
68  * stuff. */
69
70 /* ad:v2 */
71 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
72 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
73 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
74 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
75 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
76 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
77 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
78 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
79 #define ADEDOFF_PRIVDEV      (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
80 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
81 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
82 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
83 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
84
85 /* ad:ea */
86 #define ADEDOFF_FINDERI_EA    (AD_HEADER_LEN + ADEID_NUM_EA * AD_ENTRY_LEN)
87 #define ADEDOFF_COMMENT_EA    (ADEDOFF_FINDERI_EA    + ADEDLEN_FINDERI)
88 #define ADEDOFF_FILEDATESI_EA (ADEDOFF_COMMENT_EA    + ADEDLEN_COMMENT)
89 #define ADEDOFF_AFPFILEI_EA   (ADEDOFF_FILEDATESI_EA + ADEDLEN_FILEDATESI)
90 #define ADEDOFF_PRIVDEV_EA    (ADEDOFF_AFPFILEI_EA   + ADEDLEN_AFPFILEI)
91 #define ADEDOFF_PRIVINO_EA    (ADEDOFF_PRIVDEV_EA    + ADEDLEN_PRIVDEV)
92 #define ADEDOFF_PRIVSYN_EA    (ADEDOFF_PRIVINO_EA    + ADEDLEN_PRIVINO)
93 #define ADEDOFF_PRIVID_EA     (ADEDOFF_PRIVSYN_EA    + ADEDLEN_PRIVSYN)
94
95 /* this is to prevent changing timezones from causing problems with
96    localtime volumes. the screw-up is 30 years. we use a delta of 5 years */
97 #define TIMEWARP_DELTA 157680000
98
99 struct entry {
100     uint32_t id, offset, len;
101 };
102
103 /* --------------------------- */
104 static uid_t default_uid = -1;
105
106 /* Forward declarations */
107 static int ad_mkrf(const char *path);
108 static int ad_header_read(const char *path, struct adouble *ad, const struct stat *hst);
109 static int ad_header_upgrade(struct adouble *ad, const char *name);
110
111 #ifdef HAVE_EAFD
112 static int ad_mkrf_ea(const char *path);
113 #endif
114 static int ad_header_read_ea(const char *path, struct adouble *ad, const struct stat *hst);
115 static int ad_header_upgrade_ea(struct adouble *ad, const char *name);
116 off_t ad_reso_size(const char *path, int adflags, struct adouble *ad);
117 static int ad_mkrf_osx(const char *path);
118
119
120 static struct adouble_fops ad_adouble = {
121     &ad_path,
122     &ad_mkrf,
123     &ad_rebuild_adouble_header_v2,
124     &ad_header_read,
125     &ad_header_upgrade,
126 };
127
128 static struct adouble_fops ad_adouble_ea = {
129 #ifdef HAVE_EAFD
130     &ad_path_ea,
131     &ad_mkrf_ea,
132 #else
133     &ad_path_osx,
134     &ad_mkrf_osx,
135 #endif
136     &ad_rebuild_adouble_header_ea,
137     &ad_header_read_ea,
138     &ad_header_upgrade_ea,
139 };
140
141 static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
142     {ADEID_NAME,        ADEDOFF_NAME_V2,     ADEDLEN_INIT},
143     {ADEID_COMMENT,     ADEDOFF_COMMENT_V2,  ADEDLEN_INIT},
144     {ADEID_FILEDATESI,  ADEDOFF_FILEDATESI,  ADEDLEN_FILEDATESI},
145     {ADEID_FINDERI,     ADEDOFF_FINDERI_V2,  ADEDLEN_FINDERI},
146     {ADEID_DID,         ADEDOFF_DID,         ADEDLEN_DID},
147     {ADEID_AFPFILEI,    ADEDOFF_AFPFILEI,    ADEDLEN_AFPFILEI},
148     {ADEID_SHORTNAME,   ADEDOFF_SHORTNAME,   ADEDLEN_INIT},
149     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
150     {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV,     ADEDLEN_INIT},
151     {ADEID_PRIVINO,     ADEDOFF_PRIVINO,     ADEDLEN_INIT},
152     {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN,     ADEDLEN_INIT},
153     {ADEID_PRIVID,      ADEDOFF_PRIVID,      ADEDLEN_INIT},
154     {ADEID_RFORK,       ADEDOFF_RFORK_V2,    ADEDLEN_INIT},
155     {0, 0, 0}
156 };
157
158 /* Using Extended Attributes */
159 static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
160     {ADEID_FINDERI,    ADEDOFF_FINDERI_EA,    ADEDLEN_FINDERI},
161     {ADEID_COMMENT,    ADEDOFF_COMMENT_EA,    ADEDLEN_INIT},
162     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_EA, ADEDLEN_FILEDATESI},
163     {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_EA,   ADEDLEN_AFPFILEI},
164     {ADEID_PRIVDEV,    ADEDOFF_PRIVDEV_EA,    ADEDLEN_INIT},
165     {ADEID_PRIVINO,    ADEDOFF_PRIVINO_EA,    ADEDLEN_INIT},
166     {ADEID_PRIVSYN,    ADEDOFF_PRIVSYN_EA,    ADEDLEN_INIT},
167     {ADEID_PRIVID,     ADEDOFF_PRIVID_EA,     ADEDLEN_INIT},
168     {0, 0, 0}
169 };
170
171 #define ADFLAGS2LOGSTRBUFSIZ 128
172 const char *adflags2logstr(int adflags)
173 {
174     int first = 1;
175     static char buf[ADFLAGS2LOGSTRBUFSIZ];
176
177     buf[0] = 0;
178
179     if (adflags & ADFLAGS_DF) {
180         strlcat(buf, "DF", ADFLAGS2LOGSTRBUFSIZ);
181         first = 0;
182     }
183     if (adflags & ADFLAGS_RF) {
184         if (!first)
185             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
186         strlcat(buf, "RF", ADFLAGS2LOGSTRBUFSIZ);
187         first = 0;
188     }
189     if (adflags & ADFLAGS_NORF) {
190         if (!first)
191             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
192         strlcat(buf, "NORF", ADFLAGS2LOGSTRBUFSIZ);
193         first = 0;
194     }
195     if (adflags & ADFLAGS_HF) {
196         if (!first)
197             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
198         strlcat(buf, "HF", ADFLAGS2LOGSTRBUFSIZ);
199         first = 0;
200     }
201     if (adflags & ADFLAGS_NOHF) {
202         if (!first)
203             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
204         strlcat(buf, "NOHF", ADFLAGS2LOGSTRBUFSIZ);
205         first = 0;
206     }
207     if (adflags & ADFLAGS_DIR) {
208         if (!first)
209             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
210         strlcat(buf, "DIR", ADFLAGS2LOGSTRBUFSIZ);
211         first = 0;
212     }
213     if (adflags & ADFLAGS_CHECK_OF) {
214         if (!first)
215             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
216         strlcat(buf, "OF", ADFLAGS2LOGSTRBUFSIZ);
217         first = 0;
218     }
219     if (adflags & ADFLAGS_SETSHRMD) {
220         if (!first)
221             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
222         strlcat(buf, "SHRMD", ADFLAGS2LOGSTRBUFSIZ);
223         first = 0;
224     }
225     if (adflags & ADFLAGS_RDWR) {
226         if (!first)
227             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
228         strlcat(buf, "O_RDWR", ADFLAGS2LOGSTRBUFSIZ);
229         first = 0;
230     }
231     if (adflags & ADFLAGS_RDONLY) {
232         if (!first)
233             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
234         strlcat(buf, "O_RDONLY", ADFLAGS2LOGSTRBUFSIZ);
235         first = 0;
236     }
237     if (adflags & ADFLAGS_CREATE) {
238         if (!first)
239             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
240         strlcat(buf, "O_CREAT", ADFLAGS2LOGSTRBUFSIZ);
241         first = 0;
242     }
243     if (adflags & ADFLAGS_EXCL) {
244         if (!first)
245             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
246         strlcat(buf, "O_EXCL", ADFLAGS2LOGSTRBUFSIZ);
247         first = 0;
248     }
249     if (adflags & ADFLAGS_TRUNC) {
250         if (!first)
251             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
252         strlcat(buf, "O_TRUNC", ADFLAGS2LOGSTRBUFSIZ);
253         first = 0;
254     }
255
256     return buf;
257 }
258
259 #define OPENFLAGS2LOGSTRBUFSIZ 128
260 const char *openflags2logstr(int oflags)
261 {
262     int first = 1;
263     static char buf[OPENFLAGS2LOGSTRBUFSIZ];
264
265     buf[0] = 0;
266
267     if ((oflags & O_RDONLY) || (oflags == O_RDONLY)) {
268         strlcat(buf, "O_RDONLY", OPENFLAGS2LOGSTRBUFSIZ);
269         first = 0;
270     }
271     if (oflags & O_RDWR) {
272         if (!first)
273             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
274         strlcat(buf, "O_RDWR", OPENFLAGS2LOGSTRBUFSIZ);
275         first = 0;
276     }
277     if (oflags & O_CREAT) {
278         if (!first)
279             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
280         strlcat(buf, "O_CREAT", OPENFLAGS2LOGSTRBUFSIZ);
281         first = 0;
282     }
283     if (oflags & O_TRUNC) {
284         if (!first)
285             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
286         strlcat(buf, "O_TRUNC", OPENFLAGS2LOGSTRBUFSIZ);
287         first = 0;
288     }
289     if (oflags & O_EXCL) {
290         if (!first)
291             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
292         strlcat(buf, "O_EXCL", OPENFLAGS2LOGSTRBUFSIZ);
293         first = 0;
294     }
295     return buf;
296 }    
297
298 static uint32_t get_eid(uint32_t eid)
299 {
300     if (eid <= 15)
301         return eid;
302     if (eid == AD_DEV)
303         return ADEID_PRIVDEV;
304     if (eid == AD_INO)
305         return ADEID_PRIVINO;
306     if (eid == AD_SYN)
307         return ADEID_PRIVSYN;
308     if (eid == AD_ID)
309         return ADEID_PRIVID;
310
311     return 0;
312 }
313
314
315 /**
316  * Initialize offset pointers
317  */
318 int ad_init_offsets(struct adouble *ad)
319 {
320     const struct entry  *eid;
321
322     if (ad->ad_magic == AD_MAGIC)
323         return 0;
324
325     ad->ad_magic = AD_MAGIC;
326     ad->ad_version = ad->ad_vers & 0x0f0000;
327     if (!ad->ad_version) {
328         ad->ad_version = AD_VERSION;
329     }
330
331     memset(ad->ad_data, 0, sizeof(ad->ad_data));
332
333     if (ad->ad_vers == AD_VERSION2)
334         eid = entry_order2;
335     else if (ad->ad_vers == AD_VERSION_EA)
336         eid = entry_order_ea;
337     else
338         return -1;
339
340     while (eid->id) {
341         ad->ad_eid[eid->id].ade_off = eid->offset;
342         ad->ad_eid[eid->id].ade_len = eid->len;
343         eid++;
344     }
345
346     return 0;
347 }
348
349 /* ----------------------------------- */
350 static int new_ad_header(struct adouble *ad, const char *path, struct stat *stp, int adflags)
351 {
352     const struct entry  *eid;
353     uint16_t            ashort;
354     struct stat         st;
355
356     LOG(log_debug, logtype_ad, "new_ad_header(\"%s\")", path);
357
358     if (ad_init_offsets(ad) != 0)
359         return -1;
360
361     /* set default creator/type fields */
362     memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
363     memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
364
365     /* make things invisible */
366     if ((ad->ad_options & ADVOL_INVDOTS)
367         && (*path == '.')
368         && !((adflags & ADFLAGS_DIR) && (path[1] == 0))
369         ) {
370         ashort = htons(ATTRBIT_INVISIBLE);
371         ad_setattr(ad, ashort);
372         ashort = htons(FINDERINFO_INVISIBLE);
373         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
374     }
375
376     /* put something sane in the date fields */
377     if (stp == NULL) {
378         stp = &st;
379         if (lstat(path, &st) != 0)
380             return -1;
381     }
382     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, stp->st_mtime);
383     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, stp->st_mtime);
384     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, stp->st_mtime);
385     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
386
387     return 0;
388 }
389
390 /**
391  * Read an AppleDouble buffer, returns 0 on success, -1 if an entry was malformatted
392  **/
393 static int parse_entries(struct adouble *ad, char *buf, uint16_t nentries)
394 {
395     uint32_t   eid, len, off;
396     int        ret = 0;
397
398     /* now, read in the entry bits */
399     for (; nentries > 0; nentries-- ) {
400         memcpy(&eid, buf, sizeof( eid ));
401         eid = get_eid(ntohl(eid));
402         buf += sizeof( eid );
403         memcpy(&off, buf, sizeof( off ));
404         off = ntohl( off );
405         buf += sizeof( off );
406         memcpy(&len, buf, sizeof( len ));
407         len = ntohl( len );
408         buf += sizeof( len );
409
410         ad->ad_eid[eid].ade_off = off;
411         ad->ad_eid[eid].ade_len = len;
412
413         if (!eid
414             || eid > ADEID_MAX
415             || off >= sizeof(ad->ad_data)
416             || ((eid != ADEID_RFORK) && (off + len >  sizeof(ad->ad_data))))
417         {
418             ret = -1;
419             LOG(log_warning, logtype_ad, "parse_entries: bogus eid: %u, off: %u, len: %u",
420                 (uint)eid, (uint)off, (uint)len);
421         }
422     }
423
424     return ret;
425 }
426
427 /* this reads enough of the header so that we can figure out all of
428  * the entry lengths and offsets. once that's done, we just read/mmap
429  * the rest of the header in.
430  *
431  * NOTE: we're assuming that the resource fork is kept at the end of
432  *       the file. also, mmapping won't work for the hfs fs until it
433  *       understands how to mmap header files. */
434 static int ad_header_read(const char *path, struct adouble *ad, const struct stat *hst)
435 {
436     char                *buf = ad->ad_data;
437     uint16_t            nentries;
438     int                 len;
439     ssize_t             header_len;
440     struct stat         st;
441
442     /* read the header */
443     if ((header_len = adf_pread( ad->ad_mdp, buf, AD_DATASZ2, 0)) < 0) {
444         return -1;
445     }
446     if (header_len < AD_HEADER_LEN) {
447         errno = EIO;
448         return -1;
449     }
450
451     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
452     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
453     ad->ad_magic = ntohl( ad->ad_magic );
454     ad->ad_version = ntohl( ad->ad_version );
455
456     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
457         LOG(log_error, logtype_ad, "ad_open: can't parse AppleDouble header.");
458         errno = EIO;
459         return -1;
460     }
461
462     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
463     nentries = ntohs( nentries );
464
465     /* read in all the entry headers. if we have more than the
466      * maximum, just hope that the rfork is specified early on. */
467     len = nentries*AD_ENTRY_LEN;
468
469     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
470         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
471
472     buf += AD_HEADER_LEN;
473     if (len > header_len - AD_HEADER_LEN) {
474         LOG(log_error, logtype_ad, "ad_header_read: can't read entry info.");
475         errno = EIO;
476         return -1;
477     }
478
479     /* figure out all of the entry offsets and lengths. if we aren't
480      * able to read a resource fork entry, bail. */
481     nentries = len / AD_ENTRY_LEN;
482     if (parse_entries(ad, buf, nentries) != 0) {
483         LOG(log_warning, logtype_ad, "ad_header_read(%s): malformed AppleDouble",
484             path ? fullpathname(path) : "");
485         errno = EIO;
486         return -1;
487     }
488     if (!ad_getentryoff(ad, ADEID_RFORK)
489         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
490         ) {
491         LOG(log_error, logtype_ad, "ad_header_read: problem with rfork entry offset.");
492         errno = EIO;
493         return -1;
494     }
495
496     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
497         LOG(log_error, logtype_ad, "ad_header_read: can't read in entries.");
498         errno = EIO;
499         return -1;
500     }
501
502     if (hst == NULL) {
503         hst = &st;
504         if (fstat(ad->ad_mdp->adf_fd, &st) < 0) {
505             return 1; /* fail silently */
506         }
507     }
508
509     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
510
511     return 0;
512 }
513
514 /* error here means it's not ad ._ adouble:osx file and thus we return 1 */
515 int ad_valid_header_osx(const char *path)
516 {
517     EC_INIT;
518     int fd = -1;
519     struct adouble      adosx;
520     char                *buf = &adosx.ad_data[0];
521     ssize_t             header_len;
522
523     LOG(log_debug, logtype_ad, "ad_valid_header_osx(\"%s\"): BEGIN", fullpathname(path));
524
525     EC_NEG1( fd = open(path, O_RDONLY) );
526
527     /* read the header */
528     EC_NEG1( header_len = read(fd, buf, AD_DATASZ_OSX) );
529
530     if (header_len < AD_HEADER_LEN)
531         EC_FAIL;
532
533     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
534     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
535     adosx.ad_magic = ntohl(adosx.ad_magic);
536     adosx.ad_version = ntohl(adosx.ad_version);
537
538     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
539         LOG(log_warning, logtype_ad, "ad_valid_header_osx(\"%s\"): not an adouble:osx file", fullpathname(path));
540         EC_FAIL;
541     }
542
543     if (strncmp(buf + ADEDOFF_FILLER, "Mac OS X", strlen("Mac OS X")) == 0)
544         /*
545          * It's a split fork created by OS X, it's not our "own" ._ file
546          * and thus not a valid header in this context.
547          * We allow enumeration and access.
548          */
549         EC_FAIL;
550
551 EC_CLEANUP:
552     LOG(log_debug, logtype_ad, "ad_valid_header_osx(\"%s\"): END: %d", fullpathname(path), ret);
553     if (fd != -1)
554         close(fd);
555     if (ret != 0)
556         return 1;
557     return 0;
558 }
559
560 /**
561  * Convert from Apple's ._ file to Netatalk
562  *
563  * Apple's AppleDouble may contain a FinderInfo entry longer then 32 bytes
564  * containing packed xattrs. Netatalk can't deal with that, so we
565  * simply discard the packed xattrs.
566  *
567  * As we call ad_open() which might result in a recursion, just to be sure
568  * use static variable in_conversion to check for that.
569  *
570  * Returns -1 in case an error occured, 0 if no conversion was done, 1 otherwise
571  **/
572 static int ad_convert_osx(const char *path, struct adouble *ad)
573 {
574     EC_INIT;
575     static bool in_conversion = false;
576     char *map;
577     int finderlen = ad_getentrylen(ad, ADEID_FINDERI);
578     ssize_t origlen;
579
580     if (in_conversion || finderlen == ADEDLEN_FINDERI)
581         return 0;
582     in_conversion = true;
583
584     LOG(log_debug, logtype_ad, "Converting OS X AppleDouble %s, FinderInfo length: %d",
585         fullpathname(path), finderlen);
586
587     origlen = ad_getentryoff(ad, ADEID_RFORK) + ad_getentrylen(ad, ADEID_RFORK);
588
589     map = mmap(NULL, origlen, PROT_WRITE, MAP_SHARED, ad_reso_fileno(ad), 0);
590     if (map == MAP_FAILED) {
591         LOG(log_error, logtype_ad, "mmap AppleDouble: %s\n", strerror(errno));
592         EC_FAIL;
593     }
594
595     memmove(map + ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI,
596             map + ad_getentryoff(ad, ADEID_RFORK),
597             ad_getentrylen(ad, ADEID_RFORK));
598
599     ad_setentrylen(ad, ADEID_FINDERI, ADEDLEN_FINDERI);
600     ad->ad_rlen = ad_getentrylen(ad, ADEID_RFORK);
601     ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(ad, ADEID_FINDERI) + ADEDLEN_FINDERI);
602
603     EC_ZERO_LOG( ftruncate(ad_reso_fileno(ad),
604                            ad_getentryoff(ad, ADEID_RFORK)
605                            + ad_getentrylen(ad, ADEID_RFORK)) );
606
607     (void)ad_rebuild_adouble_header_osx(ad, map);
608     munmap(map, origlen);
609
610     /* Create a metadata EA if one doesn't exit */
611     if (strlen(path) < 3)
612         EC_EXIT_STATUS(0);
613     struct adouble adea;
614     ad_init_old(&adea, AD_VERSION_EA, ad->ad_options);
615
616     if (ad_open(&adea, path + 2, ADFLAGS_HF | ADFLAGS_RDWR | ADFLAGS_CREATE, 0666) < 0) {
617         LOG(log_error, logtype_ad, "create metadata: %s\n", strerror(errno));
618         EC_FAIL;
619     }
620     if (adea.ad_mdp->adf_flags & O_CREAT) {
621         memcpy(ad_entry(&adea, ADEID_FINDERI),
622                ad_entry(ad, ADEID_FINDERI),
623                ADEDLEN_FINDERI);
624         ad_flush(&adea);
625     }
626     ad_close(&adea, ADFLAGS_HF);
627
628 EC_CLEANUP:
629     in_conversion = false;
630     if (ret != 0)
631         return -1;
632     return 1;
633 }
634
635 /* Read an ._ file, only uses the resofork, finderinfo is taken from EA */
636 static int ad_header_read_osx(const char *path, struct adouble *ad, const struct stat *hst)
637 {
638     EC_INIT;
639     struct adouble      adosx;
640     char                *buf = &adosx.ad_data[0];
641     uint16_t            nentries;
642     int                 len;
643     ssize_t             header_len;
644     struct stat         st;
645     int                 retry_read = 0;
646
647 reread:
648     LOG(log_debug, logtype_ad, "ad_header_read_osx: %s", path ? fullpathname(path) : "");
649     ad_init_old(&adosx, AD_VERSION_EA, ad->ad_options);
650     memset(buf, 0, sizeof(adosx.ad_data));
651     adosx.ad_rfp->adf_fd = ad_reso_fileno(ad);
652
653     /* read the header */
654     EC_NEG1( header_len = adf_pread(ad->ad_rfp, buf, AD_DATASZ_OSX, 0) );
655
656     if (header_len < AD_HEADER_LEN) {
657         errno = EIO;
658         return -1;
659     }
660
661     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
662     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
663     adosx.ad_magic = ntohl(adosx.ad_magic);
664     adosx.ad_version = ntohl(adosx.ad_version);
665
666     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
667         LOG(log_error, logtype_ad, "ad_header_read_osx: can't parse AppleDouble header");
668         errno = EIO;
669         return -1;
670     }
671
672     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
673     nentries = ntohs(nentries);
674     len = nentries * AD_ENTRY_LEN;
675
676     if (len + AD_HEADER_LEN > sizeof(adosx.ad_data))
677         len = sizeof(adosx.ad_data) - AD_HEADER_LEN;
678
679     buf += AD_HEADER_LEN;
680     if (len > header_len - AD_HEADER_LEN) {
681         LOG(log_error, logtype_ad, "ad_header_read_osx: can't read entry info.");
682         errno = EIO;
683         return -1;
684     }
685
686     nentries = len / AD_ENTRY_LEN;
687     if (parse_entries(&adosx, buf, nentries) != 0) {
688         LOG(log_warning, logtype_ad, "ad_header_read(%s): malformed AppleDouble",
689             path ? fullpathname(path) : "");
690     }
691
692     if (ad_getentrylen(&adosx, ADEID_FINDERI) != ADEDLEN_FINDERI) {
693         LOG(log_warning, logtype_ad, "Convert OS X to Netatalk AppleDouble: %s",
694             path ? fullpathname(path) : "");
695
696         if (retry_read > 0) {
697             LOG(log_error, logtype_ad, "ad_header_read_osx: %s, giving up", path ? fullpathname(path) : "");
698             errno = EIO;
699             EC_FAIL;
700         }
701         retry_read++;
702         if (ad_convert_osx(path, &adosx) == 1) {
703             goto reread;
704         }
705         errno = EIO;
706         EC_FAIL;
707     }
708
709     if (ad_getentryoff(&adosx, ADEID_RFORK) == 0
710         || ad_getentryoff(&adosx, ADEID_RFORK) > sizeof(ad->ad_data)
711         || ad_getentryoff(&adosx, ADEID_RFORK) > header_len
712         ) {
713         LOG(log_error, logtype_ad, "ad_header_read_osx: problem with rfork entry offset.");
714         errno = EIO;
715         return -1;
716     }
717
718     if (hst == NULL) {
719         hst = &st;
720         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
721     }
722
723     ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(&adosx, ADEID_RFORK));
724     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
725
726 EC_CLEANUP:
727     EC_EXIT;
728 }
729
730 static int ad_header_read_ea(const char *path, struct adouble *ad, const struct stat *hst _U_)
731 {
732     EC_INIT;
733     uint16_t nentries;
734     int      len;
735     ssize_t  header_len;
736     char     *buf = ad->ad_data;
737
738     if (ad_meta_fileno(ad) != -1)
739         header_len = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_META, ad->ad_data, AD_DATASZ_EA);
740     else
741         header_len = sys_getxattr(path, AD_EA_META, ad->ad_data, AD_DATASZ_EA);
742     if (header_len < 1) {
743         LOG(log_debug, logtype_ad, "ad_header_read_ea: %s", strerror(errno));
744         EC_FAIL;
745     }
746
747     if (header_len < AD_DATASZ_EA) {
748         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): short metadata EA", fullpathname(path));
749         errno = EINVAL;
750         EC_FAIL;
751     }
752
753     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
754     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
755
756     ad->ad_magic = ntohl( ad->ad_magic );
757     ad->ad_version = ntohl( ad->ad_version );
758
759     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
760         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): wrong magic or version", fullpathname(path));
761         errno = EINVAL;
762         EC_FAIL;
763     }
764
765     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
766     nentries = ntohs( nentries );
767     if (nentries != ADEID_NUM_EA) {
768         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): invalid number of entries: %d", fullpathname(path), nentries);
769         errno = EINVAL;
770         EC_FAIL;
771     }
772
773     /* Now parse entries */
774     if (parse_entries(ad, buf + AD_HEADER_LEN, nentries)) {
775         LOG(log_warning, logtype_ad, "ad_header_read(%s): malformed AppleDouble",
776             path ? fullpathname(path) : "");
777         errno = EINVAL;
778         EC_FAIL;
779     }
780
781     if (nentries != ADEID_NUM_EA
782         || !ad_entry(ad, ADEID_FINDERI)
783         || !ad_entry(ad, ADEID_COMMENT)
784         || !ad_entry(ad, ADEID_FILEDATESI)
785         || !ad_entry(ad, ADEID_AFPFILEI)
786         || !ad_entry(ad, ADEID_PRIVDEV)
787         || !ad_entry(ad, ADEID_PRIVINO)
788         || !ad_entry(ad, ADEID_PRIVSYN)
789         || !ad_entry(ad, ADEID_PRIVID)) {
790         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): invalid metadata EA", fullpathname(path));
791         errno = EINVAL;
792         EC_FAIL;
793     }
794
795 EC_CLEANUP:
796     if (ret != 0 && errno == EINVAL) {
797         become_root();
798         (void)sys_removexattr(path, AD_EA_META);
799         unbecome_root();
800         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): deleted invalid metadata EA", fullpathname(path), nentries);
801         errno = ENOENT;
802     }
803     EC_EXIT;
804 }
805
806 /*!
807  * Takes a path to an AppleDouble file and creates the parrent .AppleDouble directory
808  *
809  * Example:
810  * path: "/path/.AppleDouble/file"
811  * => mkdir("/path/.AppleDouble/") (in ad_mkdir())
812  */
813 static int ad_mkrf(const char *path)
814 {
815     char *slash;
816     /*
817      * Probably .AppleDouble doesn't exist, try to mkdir it.
818      */
819     if (NULL == ( slash = strrchr( path, '/' )) ) {
820         return -1;
821     }
822     *slash = '\0';
823     errno = 0;
824     if ( ad_mkdir( path, 0777 ) < 0 ) {
825         return -1;
826     }
827     *slash = '/';
828     return 0;
829 }
830
831 #ifdef HAVE_EAFD
832 static int ad_mkrf_ea(const char *path _U_)
833 {
834     AFP_PANIC("ad_mkrf_ea: dont use");
835     return 0;
836 }
837 #endif
838
839 static int ad_mkrf_osx(const char *path _U_)
840 {
841     return 0;
842 }
843
844 /* ----------------
845    if we are root change path user/ group
846    It can be a native function for BSD cf. FAQ.Q10
847    path:  pathname to chown
848    stbuf: parent directory inode
849
850    use fstat and fchown or lchown with linux?
851 */
852 #define EMULATE_SUIDDIR
853
854 static int ad_chown(const char *path, struct stat *stbuf)
855 {
856     int ret = 0;
857 #ifdef EMULATE_SUIDDIR
858     uid_t id;
859
860     if (default_uid != (uid_t)-1) {
861         /* we are root (admin) */
862         id = (default_uid)?default_uid:stbuf->st_uid;
863         ret = lchown( path, id, stbuf->st_gid );
864     }
865 #endif
866     return ret;
867 }
868
869 #define DEFMASK 07700   /* be conservative */
870
871 /* ----------------
872    return access right and inode of path parent directory
873 */
874 static int ad_mode_st(const char *path, mode_t *mode, struct stat *stbuf)
875 {
876     if (*mode == 0) {
877         return -1;
878     }
879     if (ad_stat(path, stbuf) != 0) {
880         *mode &= DEFMASK;
881         return -1;
882     }
883     *mode &= stbuf->st_mode;
884     return 0;
885 }
886
887 /* --------------------------- */
888 static int ad_header_upgrade(struct adouble *ad _U_, const char *name _U_)
889 {
890     return 0;
891 }
892
893 static int ad_header_upgrade_ea(struct adouble *ad _U_, const char *name _U_)
894 {
895     AFP_PANIC("ad_header_upgrade_ea: dont use");
896     return 0;
897 }
898
899 /*!
900  * Error handling for adouble header(=metadata) file open error
901  *
902  * We're called because opening ADFLAGS_HF caused an error.
903  * 1. In case ad_open is called with ADFLAGS_NOHF the error is suppressed.
904  * 2. Open non-existent ressource fork, this will just result in first read return EOF
905  * 3. If ad_open was called with ADFLAGS_DF we may have opened the datafork and thus
906  *    ought to close it before returning with an error condition.
907  */
908 static int ad_error(struct adouble *ad, int adflags)
909 {
910     int err = errno;
911     if (adflags & ADFLAGS_NOHF) { /* 1 */
912         return 0;
913     }
914     if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_RF) && (errno == ENOENT)) /* 2 */
915         return 0;
916     if (adflags & (ADFLAGS_DF | ADFLAGS_SETSHRMD | ADFLAGS_CHECK_OF)) { /* 3 */
917         ad_close( ad, ADFLAGS_DF );
918         err = errno;
919     }
920     return -1 ;
921 }
922
923 /*!
924  * Map ADFLAGS to open() flags
925  *
926  * @param adfile   (r) the file you really want to open: ADFLAGS_DF or ADFLAGS_HF
927  * @param adflags  (r) flags from ad_open(..., adflags, ...)
928  * @returns            mapped flags suitable for calling open()
929  */
930 static int ad2openflags(const struct adouble *ad, int adfile, int adflags)
931 {
932     int oflags = 0;
933
934     if (adflags & ADFLAGS_RDWR)
935         oflags |= O_RDWR;
936     if (adflags & ADFLAGS_RDONLY) {
937         if (((adfile == ADFLAGS_DF || adfile == ADFLAGS_RF) && (adflags & ADFLAGS_SETSHRMD))
938             /* need rw access for locks */
939             || ((adfile == ADFLAGS_HF) && (ad->ad_vers == AD_VERSION2)))
940             /* need rw access for adouble file for the case:
941              1) openfork(data+meta:O_RDONLY), 2) openfork(reso(=meta):O_RDWR) */
942             oflags |= O_RDWR;
943         else
944             oflags |= O_RDONLY;
945     }
946     if (adflags & ADFLAGS_CREATE)
947         oflags |= O_CREAT;
948     if (adflags & ADFLAGS_EXCL)
949         oflags |= O_EXCL;
950     if (adflags & ADFLAGS_TRUNC)
951         oflags |= O_TRUNC;
952
953     if (!(ad->ad_options & ADVOL_FOLLO_SYML))
954         oflags |= O_NOFOLLOW;
955
956     return oflags;
957 }
958
959 static int ad_open_df(const char *path, int adflags, mode_t mode, struct adouble *ad)
960 {
961     EC_INIT;
962     struct stat st_dir;
963     int         oflags;
964     mode_t      admode;
965     int         st_invalid = -1;
966     ssize_t     lsz;
967
968     LOG(log_debug, logtype_ad,
969         "ad_open_df(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
970         fullpathname(path), adflags2logstr(adflags),
971         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
972         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
973         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
974
975     if (ad_data_fileno(ad) != -1) {
976         /* the file is already open, but we want write access: */
977         if ((adflags & ADFLAGS_RDWR)
978             /* and it was denied the first time: */
979             && (ad->ad_data_fork.adf_flags & O_RDONLY)) {
980                 errno = EACCES;
981                 return -1;
982             }
983         /* it's not new anymore */
984         ad->ad_data_fork.adf_flags &= ~( O_TRUNC | O_CREAT );
985         ad->ad_data_fork.adf_refcount++;
986         goto EC_CLEANUP;
987     }
988
989     oflags = ad2openflags(ad, ADFLAGS_DF, adflags);
990
991     admode = mode;
992     if ((adflags & ADFLAGS_CREATE)) {
993         st_invalid = ad_mode_st(path, &admode, &st_dir);
994         if ((ad->ad_options & ADVOL_UNIXPRIV))
995             admode = mode;
996     }
997
998     ad->ad_data_fork.adf_fd = open(path, oflags, admode);
999
1000     if (ad->ad_data_fork.adf_fd == -1) {
1001         switch (errno) {
1002         case EACCES:
1003         case EPERM:
1004         case EROFS:
1005             if ((adflags & ADFLAGS_SETSHRMD) && (adflags & ADFLAGS_RDONLY)) {
1006                 oflags &= ~O_RDWR;
1007                 oflags |= O_RDONLY;
1008                 EC_NEG1( ad->ad_data_fork.adf_fd = open(path, oflags, admode) );
1009                 break;
1010             }
1011             return -1;
1012         case OPEN_NOFOLLOW_ERRNO:
1013             ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
1014             if ((lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN)) <= 0) {
1015                 free(ad->ad_data_fork.adf_syml);
1016                 EC_FAIL;
1017             }
1018             ad->ad_data_fork.adf_syml[lsz] = 0;
1019             ad->ad_data_fork.adf_fd = AD_SYMLINK;
1020             break;
1021         default:
1022             EC_FAIL;
1023         }
1024     }
1025
1026     if (!st_invalid)
1027         ad_chown(path, &st_dir); /* just created, set owner if admin (root) */
1028
1029     ad->ad_data_fork.adf_flags = oflags;
1030     adf_lock_init(&ad->ad_data_fork);
1031     ad->ad_data_fork.adf_refcount++;
1032
1033 EC_CLEANUP:
1034     LOG(log_debug, logtype_ad,
1035         "ad_open_df(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1036         fullpathname(path), adflags2logstr(adflags), ret,
1037         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1038         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1039         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1040     EC_EXIT;
1041 }
1042
1043 static int ad_open_hf_v2(const char *path, int adflags, mode_t mode, struct adouble *ad)
1044 {
1045     EC_INIT;
1046     struct stat st_dir;
1047     struct stat st_meta;
1048     struct stat *pst = NULL;
1049     const char  *ad_p;
1050     int         oflags, nocreatflags, opened = 0;
1051     mode_t      admode;
1052     int         st_invalid = -1;
1053
1054     LOG(log_debug, logtype_ad,
1055         "ad_open_hf_v2(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1056         fullpathname(path), adflags2logstr(adflags),
1057         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1058         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1059         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1060
1061     if (ad_meta_fileno(ad) != -1) {
1062         /* the file is already open, but we want write access: */
1063         if ((adflags & ADFLAGS_RDWR) &&
1064             /* and it was already denied: */
1065             (ad->ad_mdp->adf_flags & O_RDONLY)) {
1066             errno = EACCES;
1067             EC_FAIL;
1068         }
1069         ad_refresh(path, ad);
1070         /* it's not new anymore */
1071         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
1072         ad->ad_mdp->adf_refcount++;
1073         goto EC_CLEANUP;
1074     }
1075
1076     ad_p = ad->ad_ops->ad_path(path, adflags);
1077     oflags = ad2openflags(ad, ADFLAGS_HF, adflags);
1078     LOG(log_debug, logtype_ad,"ad_open_hf_v2(\"%s\"): open flags: %s",
1079         fullpathname(path), openflags2logstr(oflags));
1080     nocreatflags = oflags & ~(O_CREAT | O_EXCL);
1081
1082     ad_meta_fileno(ad) = open(ad_p, nocreatflags);
1083
1084     if (ad_meta_fileno(ad) != -1) {
1085         ad->ad_mdp->adf_flags = nocreatflags;
1086     } else {
1087         switch (errno) {
1088         case EACCES:
1089         case EPERM:
1090         case EROFS:
1091             if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_SETSHRMD)) {
1092                 nocreatflags &= ~O_RDWR;
1093                 nocreatflags |= O_RDONLY;
1094                 EC_NEG1( ad_meta_fileno(ad) = open(ad_p, nocreatflags) );
1095                 ad->ad_mdp->adf_flags = nocreatflags;
1096                 break;
1097             }
1098             EC_FAIL;
1099         case ENOENT:
1100             if (!(oflags & O_CREAT))
1101                 EC_FAIL;
1102             /*
1103              * We're expecting to create a new adouble header file here
1104              */
1105             LOG(log_debug, logtype_ad, "ad_open(\"%s\"): creating adouble file",
1106                 fullpathname(path));
1107             admode = mode;
1108             errno = 0;
1109             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1110             if ((ad->ad_options & ADVOL_UNIXPRIV))
1111                 admode = mode;
1112             admode = ad_hf_mode(admode);
1113             if (errno == ENOENT) {
1114                 EC_NEG1_LOG( ad->ad_ops->ad_mkrf(ad_p) );
1115                 admode = mode;
1116                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1117                 if ((ad->ad_options & ADVOL_UNIXPRIV))
1118                     admode = mode;
1119                 admode = ad_hf_mode(admode);
1120             }
1121
1122             /* retry with O_CREAT */
1123             EC_NEG1( ad_meta_fileno(ad) = open(ad_p, oflags, admode) );
1124             ad->ad_mdp->adf_flags = oflags;
1125             /* just created, set owner if admin owner (root) */
1126             if (!st_invalid)
1127                 ad_chown(ad_p, &st_dir);
1128             break;
1129         default:
1130             EC_FAIL;
1131         }
1132     }
1133
1134     /* Now we've got a new opened fd, we need to check that in the error case */
1135     opened = 1;
1136
1137     if (!(ad->ad_mdp->adf_flags & O_CREAT)) {
1138         /* check for 0 length files, treat them as new. */
1139         if (fstat(ad->ad_mdp->adf_fd, &st_meta) == 0) {
1140             if (st_meta.st_size == 0)
1141                 ad->ad_mdp->adf_flags |= O_TRUNC;
1142             else
1143                 /* we have valid data in st_meta stat structure, reused it in ad_header_read */
1144                 pst = &st_meta;
1145         }
1146     }
1147
1148     adf_lock_init(ad->ad_mdp);
1149     ad->ad_mdp->adf_refcount = 1;
1150
1151     if ((ad->ad_mdp->adf_flags & ( O_TRUNC | O_CREAT ))) {
1152         /* This is a new adouble header file, create it */
1153         EC_NEG1_LOG( new_ad_header(ad, path, pst, adflags) );
1154         ad_flush(ad);
1155     } else {
1156         /* Read the adouble header in and parse it.*/
1157         EC_NEG1_LOG( ad->ad_ops->ad_header_read(path, ad, pst) );
1158     }
1159
1160 EC_CLEANUP:
1161     if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
1162         close(ad_meta_fileno(ad));
1163         ad_meta_fileno(ad) = -1;
1164         ad->ad_mdp->adf_refcount = 0;
1165     }
1166     LOG(log_debug, logtype_ad,
1167         "ad_open_hf_v2(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1168         fullpathname(path), adflags2logstr(adflags), ret,
1169         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1170         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1171         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1172     EC_EXIT;
1173 }
1174
1175 static int ad_open_hf_ea(const char *path, int adflags, int mode, struct adouble *ad)
1176 {
1177     EC_INIT;
1178     int oflags;
1179     int opened = 0;
1180
1181     LOG(log_debug, logtype_ad,
1182         "ad_open_hf_ea(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1183         fullpathname(path), adflags2logstr(adflags),
1184         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1185         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1186         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1187
1188     oflags = ad2openflags(ad, ADFLAGS_DF, adflags) & ~(O_CREAT | O_TRUNC);
1189
1190     if (ad_meta_fileno(ad) == AD_SYMLINK)
1191         goto EC_CLEANUP;
1192
1193     if (ad_meta_fileno(ad) != -1) {
1194         /* the file is already open, but we want write access: */
1195         if ((oflags & O_RDWR) &&
1196             /* and it was already denied: */
1197             (ad->ad_mdp->adf_flags & O_RDONLY)) {
1198             LOG(log_error, logtype_ad, "ad_open_hf_ea(%s): rw request for ro file: %s",
1199                 fullpathname(path), strerror(errno));
1200             errno = EACCES;
1201             EC_FAIL;
1202         }
1203         /* it's not new anymore */
1204         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
1205     } else {
1206         if (oflags & O_RDWR) {
1207             /* Fo a RDONLY adouble we just use sys_lgetxattr instead if sys_fgetxattr */
1208             if (adflags & ADFLAGS_DIR)
1209                 /* For directories we open the directory RDONYL so we can later fchdir()  */
1210                 oflags = (oflags & ~O_RDWR) | O_RDONLY;
1211             LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): opening base file for meta adouble EA", path);
1212             EC_NEG1(ad_meta_fileno(ad) = open(path, oflags));
1213             opened = 1;
1214             ad->ad_mdp->adf_flags = oflags;
1215         }
1216     }
1217
1218     /* Read the adouble header in and parse it.*/
1219     if (ad->ad_ops->ad_header_read(path, ad, NULL) != 0) {
1220         if (!(adflags & ADFLAGS_CREATE)) {
1221             LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): can't read metadata EA", path);
1222             errno = ENOENT;
1223             EC_FAIL;
1224         }
1225         if ((adflags & ADFLAGS_CREATE) && (ad->ad_options & ADVOL_RO)) {
1226             errno = EROFS;
1227             EC_FAIL;
1228         }
1229
1230         LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): creating metadata EA", path);
1231
1232         /* It doesnt exist, EPERM or another error */
1233         if (!(errno == ENOATTR || errno == ENOENT)) {
1234             LOG(log_error, logtype_ad, "ad_open_hf_ea: unexpected: %s", strerror(errno));
1235             EC_FAIL;
1236         }
1237
1238         /* Create one */
1239         EC_NEG1_LOG(new_ad_header(ad, path, NULL, adflags));
1240         ad->ad_mdp->adf_flags |= O_CREAT; /* mark as just created */
1241         ad_flush(ad);
1242         LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): created metadata EA", path);
1243     }
1244
1245     if (ad_meta_fileno(ad) != -1)
1246         ad->ad_mdp->adf_refcount++;
1247     ad->ad_rlen = ad_reso_size(path, adflags, ad);
1248
1249 EC_CLEANUP:
1250     if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
1251         close(ad_meta_fileno(ad));
1252         ad_meta_fileno(ad) = -1;
1253         ad->ad_mdp->adf_refcount = 0;
1254     }
1255     LOG(log_debug, logtype_ad,
1256         "ad_open_hf_ea(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1257         fullpathname(path), adflags2logstr(adflags), ret,
1258         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1259         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1260         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1261         
1262     EC_EXIT;
1263 }
1264
1265 static int ad_open_hf(const char *path, int adflags, int mode, struct adouble *ad)
1266 {
1267     int ret = 0;
1268
1269     ad->ad_meta_refcount++;
1270
1271     switch (ad->ad_vers) {
1272     case AD_VERSION2:
1273         ret = ad_open_hf_v2(path, adflags, mode, ad);
1274         break;
1275     case AD_VERSION_EA:
1276         ret = ad_open_hf_ea(path, adflags, mode, ad);
1277         break;
1278     default:
1279         ret = -1;
1280         break;
1281     }
1282
1283     if (ret != 0) {
1284         ad->ad_meta_refcount--;
1285         ret = ad_error(ad, adflags);
1286     }
1287
1288     return ret;
1289 }
1290
1291 /*!
1292  * Get resofork length for adouble:ea, parameter 'ad' may be NULL
1293  */
1294 off_t ad_reso_size(const char *path, int adflags, struct adouble *ad)
1295 {
1296     EC_INIT;
1297     struct stat st;
1298     off_t rlen;
1299
1300     if (adflags & ADFLAGS_DIR)
1301         EC_FAIL;
1302
1303     LOG(log_debug, logtype_ad, "ad_reso_size(\"%s\"): BEGIN", path);
1304
1305 #ifdef HAVE_EAFD
1306     ssize_t easz;
1307
1308     if (ad && ad_reso_fileno(ad) != -1) {
1309         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
1310         rlen = st.st_size;
1311     } else if (ad && ad_meta_fileno(ad) != -1) {
1312         EC_NEG1( (rlen = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_RESO, NULL, 0)) );
1313     } else {
1314         EC_NEG1( (rlen = sys_lgetxattr(path, AD_EA_RESO, NULL, 0)) );
1315     }
1316
1317 #else
1318     const char *rfpath;
1319     EC_NULL_LOG( rfpath = ad_path_osx(path, adflags));
1320     EC_ZERO( lstat(rfpath, &st));
1321     if (st.st_size > ADEDOFF_RFORK_OSX)
1322         rlen = st.st_size - ADEDOFF_RFORK_OSX;
1323     else
1324         rlen = 0;
1325 #endif
1326
1327     LOG(log_debug, logtype_ad, "ad_reso_size(\"%s\"): size: %zd", path, rlen);
1328
1329 EC_CLEANUP:
1330     if (ret != 0)
1331         rlen = 0;
1332     return rlen;
1333 }
1334
1335 static int ad_open_rf_v2(const char *path, int adflags, int mode, struct adouble *ad)
1336 {
1337     EC_INIT;
1338
1339     /*
1340      * ad_open_hf_v2() does the work, but if it failed and adflags are ADFLAGS_NOHF | ADFLAGS_RF
1341      * ad_open_hf_v2() didn't give an error, but we're supposed to return a reso fork fd
1342      */
1343
1344     LOG(log_debug, logtype_ad, "ad_open_rf_v2(\"%s\"): BEGIN", fullpathname(path));
1345
1346     if (!AD_META_OPEN(ad) && !(adflags & (ADFLAGS_NORF | ADFLAGS_RDONLY)))
1347         EC_FAIL;
1348     if (AD_META_OPEN(ad))
1349         ad->ad_reso_refcount++;
1350
1351 EC_CLEANUP:
1352     LOG(log_debug, logtype_ad, "ad_open_rf_v2(\"%s\"): END: %d", fullpathname(path), ret);
1353     EC_EXIT;
1354 }
1355
1356 static int ad_open_rf_ea(const char *path, int adflags, int mode, struct adouble *ad)
1357 {
1358     EC_INIT;
1359     int oflags;
1360     int opened = 0;
1361     int closeflags = adflags & (ADFLAGS_DF | ADFLAGS_HF);
1362 #ifndef HAVE_EAFD
1363     const char *rfpath;
1364     struct stat st;
1365 #endif
1366
1367     LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): BEGIN", fullpathname(path));
1368
1369     oflags = ad2openflags(ad, ADFLAGS_RF, adflags) & ~O_CREAT;
1370
1371     if (ad_reso_fileno(ad) != -1) {
1372         /* the file is already open, but we want write access: */
1373         if ((oflags & O_RDWR)
1374             /* and it was already denied: */
1375             && (ad->ad_rfp->adf_flags & O_RDONLY)) {
1376             errno = EACCES;
1377             EC_FAIL;
1378         }
1379         ad->ad_rfp->adf_flags &= ~( O_TRUNC | O_CREAT );
1380         ad->ad_reso_refcount++;
1381         ad->ad_rfp->adf_refcount++;
1382         EC_NEG1_LOG( ad->ad_rlen = ad_reso_size(path, adflags, ad));
1383         goto EC_CLEANUP;
1384     }
1385 #ifdef HAVE_EAFD
1386     if (ad_meta_fileno(ad) < 0)
1387         EC_FAIL;
1388     if ((ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad), AD_EA_RESO, oflags)) == -1) {
1389         if (!(adflags & ADFLAGS_CREATE)) {
1390             switch (errno) {
1391             case EACCES:
1392             case EPERM:
1393             case EROFS:
1394                 if (!(adflags & ADFLAGS_RDONLY)) {
1395                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(path), strerror(errno));
1396                     EC_FAIL;
1397                 }
1398                 oflags &= ~O_RDWR;
1399                 oflags |= O_RDONLY;
1400                 if ((ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad), AD_EA_RESO, oflags)) == -1) {
1401                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(path), strerror(errno));
1402                     EC_FAIL;
1403                 }
1404                 break;
1405             case ENOENT:
1406                 EC_EXIT_STATUS(0);
1407             default:
1408                 LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(path), strerror(errno));
1409                 EC_FAIL;
1410             }
1411         } else {
1412             oflags |= O_CREAT;
1413             EC_NEG1_LOG( ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad),
1414                                                              AD_EA_RESO, oflags, 0666) );
1415         }
1416     }
1417 #else
1418     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags) );
1419     if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1420         if (!(adflags & ADFLAGS_CREATE)) {
1421             switch (errno) {
1422             case EACCES:
1423             case EPERM:
1424             case EROFS:
1425                 if (!(adflags & ADFLAGS_RDONLY)) {
1426                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(rfpath), strerror(errno));
1427                     EC_FAIL;
1428                 }
1429                 oflags &= ~O_RDWR;
1430                 oflags |= O_RDONLY;
1431                 if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1432                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(rfpath), strerror(errno));
1433                     EC_FAIL;
1434                 }
1435                 break;
1436             case ENOENT:
1437                 EC_EXIT_STATUS(0);
1438             default:
1439                 LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(rfpath), strerror(errno));
1440                 EC_FAIL;
1441             }
1442         } else {
1443             oflags |= O_CREAT;
1444             EC_NEG1_LOG( ad_reso_fileno(ad) = open(rfpath, oflags, mode) );
1445             LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): created adouble rfork: \"%s\"",
1446                 path, rfpath);
1447         }
1448     }
1449 #endif
1450     opened = 1;
1451     ad->ad_rfp->adf_refcount = 1;
1452     ad->ad_rfp->adf_flags = oflags;
1453     ad->ad_reso_refcount++;
1454
1455 #ifndef HAVE_EAFD
1456     EC_ZERO_LOG( fstat(ad_reso_fileno(ad), &st) );
1457     if (ad->ad_rfp->adf_flags & O_CREAT) {
1458         /* This is a new adouble header file, create it */
1459         LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): created adouble rfork, initializing: \"%s\"",
1460             path, rfpath);
1461         EC_NEG1_LOG( new_ad_header(ad, path, NULL, adflags) );
1462         LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): created adouble rfork, flushing: \"%s\"",
1463             path, rfpath);
1464         ad_flush(ad);
1465     } else {
1466         /* Read the adouble header */
1467         LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): reading adouble rfork: \"%s\"",
1468             path, rfpath);
1469         EC_NEG1_LOG( ad_header_read_osx(rfpath, ad, &st) );
1470     }
1471 #endif
1472
1473     ad->ad_rlen = ad_reso_size(path, adflags, ad);
1474
1475 EC_CLEANUP:
1476     if (ret != 0) {
1477         if (opened && (ad_reso_fileno(ad) != -1)) {
1478             close(ad_reso_fileno(ad));
1479             ad_reso_fileno(ad) = -1;
1480             ad->ad_reso_refcount--;
1481             ad->ad_rfp->adf_refcount = 0;
1482         }
1483         if (adflags & ADFLAGS_NORF) {
1484             ret = 0;
1485         } else {
1486             int err = errno;
1487             (void)ad_close(ad, closeflags);
1488             errno = err;
1489         }
1490         ad->ad_rlen = 0;
1491     }
1492
1493     LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): END: %d", fullpathname(path), ret);
1494
1495     EC_EXIT;
1496 }
1497
1498 /*!
1499  * Open ressource fork
1500  */
1501 static int ad_open_rf(const char *path, int adflags, int mode, struct adouble *ad)
1502 {
1503     int ret = 0;
1504
1505     switch (ad->ad_vers) {
1506     case AD_VERSION2:
1507         ret = ad_open_rf_v2(path, adflags, mode, ad);
1508         break;
1509     case AD_VERSION_EA:
1510         ret = ad_open_rf_ea(path, adflags, mode, ad);
1511         break;
1512     default:
1513         ret = -1;
1514         break;
1515     }
1516
1517     return ret;
1518 }
1519
1520 /***********************************************************************************
1521  * API functions
1522  ********************************************************************************* */
1523
1524 off_t ad_getentryoff(const struct adouble *ad, int eid)
1525 {
1526     if (ad->ad_vers == AD_VERSION2)
1527         return ad->ad_eid[eid].ade_off;
1528
1529     switch (eid) {
1530     case ADEID_DFORK:
1531         return 0;
1532     case ADEID_RFORK:
1533 #ifdef HAVE_EAFD
1534         return 0;
1535 #else
1536         return ad->ad_eid[eid].ade_off;
1537 #endif
1538     default:
1539         return ad->ad_eid[eid].ade_off;
1540     }
1541     /* deadc0de */
1542     AFP_PANIC("What am I doing here?");
1543 }
1544
1545 const char *ad_path_ea( const char *path, int adflags _U_)
1546 {
1547     return path;
1548 }
1549
1550 const char *ad_path_osx(const char *path, int adflags _U_)
1551 {
1552     static char pathbuf[ MAXPATHLEN + 1];
1553     char    c, *slash, buf[MAXPATHLEN + 1];
1554
1555     if (!strcmp(path,".")) {
1556         /* fixme */
1557         getcwd(buf, MAXPATHLEN);
1558     }
1559     else {
1560         strlcpy(buf, path, MAXPATHLEN +1);
1561     }
1562     if (NULL != ( slash = strrchr( buf, '/' )) ) {
1563         c = *++slash;
1564         *slash = '\0';
1565         strlcpy( pathbuf, buf, MAXPATHLEN +1);
1566         *slash = c;
1567     } else {
1568         pathbuf[ 0 ] = '\0';
1569         slash = buf;
1570     }
1571     strlcat( pathbuf, "._", MAXPATHLEN  +1);
1572     strlcat( pathbuf, slash, MAXPATHLEN +1);
1573     return pathbuf;
1574 }
1575
1576 /*
1577  * Put the .AppleDouble where it needs to be:
1578  *
1579  *      /   a/.AppleDouble/b
1580  *  a/b
1581  *      \   b/.AppleDouble/.Parent
1582  *
1583  * FIXME: should do something for pathname > MAXPATHLEN
1584  */
1585 const char *ad_path( const char *path, int adflags)
1586 {
1587     static char pathbuf[ MAXPATHLEN + 1];
1588     const char *slash;
1589     size_t  l ;
1590
1591     if ( adflags & ADFLAGS_DIR ) {
1592         l = strlcpy( pathbuf, path, sizeof(pathbuf));
1593
1594         if ( l && l < MAXPATHLEN) {
1595             pathbuf[l++] = '/';
1596         }
1597         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
1598     } else {
1599         if (NULL != ( slash = strrchr( path, '/' )) ) {
1600             slash++;
1601             l = slash - path;
1602             /* XXX we must return NULL here and test in the caller */
1603             if (l > MAXPATHLEN)
1604                 l = MAXPATHLEN;
1605             memcpy( pathbuf, path, l);
1606         } else {
1607             l = 0;
1608             slash = path;
1609         }
1610         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
1611         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
1612     }
1613
1614     return( pathbuf );
1615 }
1616
1617 /* -------------------------
1618  * Support inherited protection modes for AppleDouble files.  The supplied
1619  * mode is ANDed with the parent directory's mask value in lieu of "umask",
1620  * and that value is returned.
1621  */
1622 char *ad_dir(const char *path)
1623 {
1624     static char     modebuf[ MAXPATHLEN + 1];
1625     char        *slash;
1626     /*
1627      * For a path with directories in it, remove the final component
1628      * (path or subdirectory name) to get the name we want to stat.
1629      * For a path which is just a filename, use "." instead.
1630      */
1631     slash = strrchr( path, '/' );
1632     if (slash) {
1633         size_t len;
1634
1635         len = slash - path;
1636         if (len >= MAXPATHLEN) {
1637             errno = ENAMETOOLONG;
1638             return NULL;  /* can't do it */
1639         }
1640         memcpy( modebuf, path, len );
1641         modebuf[len] = '\0';
1642         /* is last char a '/' ? */
1643         if (slash[1] == 0) {
1644             slash = modebuf+ len;
1645             /* remove them */
1646             while (modebuf < slash && slash[-1] == '/') {
1647                 --slash;
1648             }
1649             if (modebuf == slash) {
1650                 goto use_cur;
1651             }
1652             *slash = '\0';
1653             while (modebuf < slash && *slash != '/') {
1654                 --slash;
1655             }
1656             if (modebuf == slash) {
1657                 goto use_cur;
1658             }
1659             *slash = '\0';      /* remove pathname component */
1660         }
1661         return modebuf;
1662     }
1663 use_cur:
1664     modebuf[0] = '.';   /* use current directory */
1665     modebuf[1] = '\0';
1666     return modebuf;
1667 }
1668
1669 int ad_setfuid(const uid_t id)
1670 {
1671     default_uid = id;
1672     return 0;
1673 }
1674
1675 /* ---------------- */
1676 uid_t ad_getfuid(void)
1677 {
1678     return default_uid;
1679 }
1680
1681 /* ----------------
1682    stat path parent directory
1683 */
1684 int ad_stat(const char *path, struct stat *stbuf)
1685 {
1686     char *p;
1687
1688     p = ad_dir(path);
1689     if (!p)
1690         return -1;
1691     return stat( p, stbuf );
1692 }
1693
1694 /* ----------------
1695    return access right of path parent directory
1696 */
1697 int ad_mode( const char *path, mode_t mode)
1698 {
1699     struct stat     stbuf;
1700     ad_mode_st(path, &mode, &stbuf);
1701     return mode;
1702 }
1703
1704 /*
1705  * Use mkdir() with mode bits taken from ad_mode().
1706  */
1707 int ad_mkdir( const char *path, mode_t mode)
1708 {
1709     int ret;
1710     int st_invalid;
1711     struct stat stbuf;
1712
1713     LOG(log_debug, logtype_ad, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
1714         path, mode, getcwdpath());
1715
1716     st_invalid = ad_mode_st(path, &mode, &stbuf);
1717     ret = mkdir( path, mode );
1718     if (ret || st_invalid)
1719         return ret;
1720     ad_chown(path, &stbuf);
1721
1722     return ret;
1723 }
1724
1725 static void ad_init_func(struct adouble *ad)
1726 {
1727     switch (ad->ad_vers) {
1728     case AD_VERSION2:
1729         ad->ad_ops = &ad_adouble;
1730         ad->ad_rfp = &ad->ad_resource_fork;
1731         ad->ad_mdp = &ad->ad_resource_fork;
1732         break;
1733     case AD_VERSION_EA:
1734         ad->ad_ops = &ad_adouble_ea;
1735         ad->ad_rfp = &ad->ad_resource_fork;
1736         ad->ad_mdp = &ad->ad_data_fork;
1737         break;
1738     default:
1739         AFP_PANIC("ad_init: unknown AD version");
1740     }
1741
1742
1743     ad_data_fileno(ad) = -1;
1744     ad_reso_fileno(ad) = -1;
1745     ad_meta_fileno(ad) = -1;
1746     ad->ad_refcount = 1;
1747     ad->ad_rlen = 0;
1748     return;
1749 }
1750
1751 void ad_init_old(struct adouble *ad, int flags, int options)
1752 {
1753     memset(ad, 0, sizeof(struct adouble));
1754     ad->ad_vers = flags;
1755     ad->ad_options = options;
1756     ad_init_func(ad);
1757 }
1758
1759 void ad_init(struct adouble *ad, const struct vol * restrict vol)
1760 {
1761     memset(ad, 0, sizeof(struct adouble));
1762     ad->ad_vers = vol->v_adouble;
1763     ad->ad_options = vol->v_ad_options;
1764     ad_init_func(ad);
1765 }
1766
1767 /*!
1768  * Open data-, metadata(header)- or ressource fork
1769  *
1770  * ad_open(struct adouble *ad, const char *path, int adflags, int flags)
1771  * ad_open(struct adouble *ad, const char *path, int adflags, int flags, mode_t mode)
1772  *
1773  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1774  * @code
1775  *      struct adoube ad;
1776  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1777  * @endcode
1778  *
1779  * Open a files data fork, metadata fork or ressource fork.
1780  *
1781  * @param ad        (rw) pointer to struct adouble
1782  * @param path      (r)  Path to file or directory
1783  * @param adflags   (r)  Flags specifying which fork to open, can be or'd:
1784  *                         ADFLAGS_DF:        open data fork
1785  *                         ADFLAGS_RF:        open ressource fork
1786  *                         ADFLAGS_HF:        open header (metadata) file
1787  *                         ADFLAGS_NOHF:      it's not an error if header file couldn't be opened
1788  *                         ADFLAGS_NORF:      it's not an error if reso fork couldn't be opened
1789  *                         ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags
1790  *
1791  *                       Access mode for the forks:
1792  *                         ADFLAGS_RDONLY:    open read only
1793  *                         ADFLAGS_RDWR:      open read write
1794  *
1795  *                       Creation flags:
1796  *                         ADFLAGS_CREATE:    create if not existing
1797  *                         ADFLAGS_TRUNC:     truncate
1798  *
1799  *                       Special flags:
1800  *                         ADFLAGS_CHECK_OF:  check for open forks from us and other afpd's
1801  *                         ADFLAGS_SETSHRMD:  this adouble struct will be used to set sharemode locks.
1802  *                                            This basically results in the files being opened RW instead of RDONLY.
1803  * @param mode      (r)  mode used with O_CREATE
1804  *
1805  * The open mode flags (rw vs ro) have to take into account all the following requirements:
1806  * - we remember open fds for files because me must avoid a single close releasing fcntl locks for other
1807  *   fds of the same file
1808  *
1809  * @returns 0 on success, any other value indicates an error
1810  */
1811 int ad_open(struct adouble *ad, const char *path, int adflags, ...)
1812 {
1813     EC_INIT;
1814     va_list args;
1815     mode_t mode = 0;
1816
1817     LOG(log_debug, logtype_ad,
1818         "ad_open(\"%s\", %s): BEGIN {d: %d, m: %d, r: %d}"
1819         "[dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1820         fullpathname(path), adflags2logstr(adflags),
1821         ad->ad_data_refcount, ad->ad_meta_refcount, ad->ad_reso_refcount,
1822         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1823         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1824         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1825
1826     if (adflags & ADFLAGS_CHECK_OF)
1827         /* Checking for open forks requires sharemode lock support (ie RDWR instead of RDONLY) */
1828         adflags |= ADFLAGS_SETSHRMD;
1829
1830     if (adflags & ADFLAGS_SETSHRMD)
1831         /* sharemode locks are stored in the data fork */
1832         adflags |= ADFLAGS_DF;
1833
1834     if (ad->ad_vers == AD_VERSION2) {
1835         if (adflags & ADFLAGS_RF)
1836             adflags |= ADFLAGS_HF;
1837         if (adflags & ADFLAGS_NORF)
1838             adflags |= ADFLAGS_NOHF;
1839     }
1840
1841     if (ad->ad_inited != AD_INITED) {
1842         ad->ad_adflags = adflags;
1843         ad->ad_inited = AD_INITED;
1844     } else {
1845         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1846         if (ad->ad_resource_fork.adf_refcount > 0)
1847             ad->ad_open_forks |= ATTRBIT_ROPEN;
1848     }
1849
1850     va_start(args, adflags);
1851     if (adflags & ADFLAGS_CREATE)
1852         mode = (sizeof(mode_t) < sizeof(int) ? va_arg (args, int) : va_arg (args, mode_t));
1853     va_end(args);
1854
1855     if (adflags & ADFLAGS_DF) {
1856         ad->ad_data_refcount++;
1857         if (ad_open_df(path, adflags, mode, ad) != 0) {
1858             ad->ad_data_refcount--;
1859             EC_FAIL;
1860         }
1861     }
1862
1863     if (adflags & ADFLAGS_HF) {
1864         if (ad_open_hf(path, adflags, mode, ad) != 0) {
1865             EC_FAIL;
1866         }
1867     }
1868
1869     if (adflags & ADFLAGS_RF) {
1870         if (ad_open_rf(path, adflags, mode, ad) != 0) {
1871             EC_FAIL;
1872         }
1873     }
1874
1875     if (adflags & ADFLAGS_CHECK_OF) {
1876         ad->ad_open_forks |= ad_openforks(ad, ad->ad_open_forks);
1877     }
1878
1879 EC_CLEANUP:
1880     LOG(log_debug, logtype_ad,
1881         "ad_open(\"%s\"): END: %d {d: %d, m: %d, r: %d}"
1882         "[dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1883         fullpathname(path), ret,
1884         ad->ad_data_refcount, ad->ad_meta_refcount, ad->ad_reso_refcount,
1885         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1886         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1887         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1888
1889     EC_EXIT;
1890 }
1891
1892 /*!
1893  * @brief open metadata, possibly as root
1894  *
1895  * Return only metadata but try very hard ie at first try as user, then try as root.
1896  *
1897  * @param name  name of file/dir
1898  * @param flags ADFLAGS_DIR: name is a directory \n
1899  *              ADFLAGS_CHECK_OF: test if name is open by us or another afpd process
1900  *
1901  * @param adp   pointer to struct adouble
1902  */
1903 int ad_metadata(const char *name, int flags, struct adouble *adp)
1904 {
1905     int   ret, err, oflags;
1906
1907     /* Sanitize flags */
1908     oflags = (flags & (ADFLAGS_CHECK_OF | ADFLAGS_DIR)) | ADFLAGS_HF | ADFLAGS_RDONLY;    
1909
1910     if ((ret = ad_open(adp, name, oflags)) < 0 && errno == EACCES) {
1911         become_root();
1912         ret = ad_open(adp, name, oflags);
1913         unbecome_root();
1914         err = errno;
1915         errno = err;
1916     }
1917
1918     return ret;
1919 }
1920
1921 /*
1922  * @brief openat like wrapper for ad_metadata
1923  */
1924 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1925 {
1926     int ret = 0;
1927     int cwdfd = -1;
1928
1929     if (dirfd != -1) {
1930         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1931             ret = -1;
1932             goto exit;
1933         }
1934     }
1935
1936     if (ad_metadata(name, flags, adp) < 0) {
1937         ret = -1;
1938         goto exit;
1939     }
1940
1941     if (dirfd != -1) {
1942
1943         if (fchdir(cwdfd) != 0) {
1944             LOG(log_error, logtype_ad, "ad_openat: cant chdir back, exiting");
1945             exit(EXITERR_SYS);
1946         }
1947     }
1948
1949 exit:
1950     if (cwdfd != -1)
1951         close(cwdfd);
1952
1953     return ret;
1954
1955 }
1956
1957 int ad_refresh(const char *path, struct adouble *ad)
1958 {
1959     switch (ad->ad_vers) {
1960     case AD_VERSION2:
1961         if (ad_meta_fileno(ad) == -1)
1962             return -1;
1963         return ad->ad_ops->ad_header_read(NULL, ad, NULL);
1964         break;
1965     case AD_VERSION_EA:
1966 #ifdef HAVE_EAFD
1967         if (AD_META_OPEN(ad)) {
1968             if (ad_data_fileno(ad) == -1)
1969                 return -1;
1970             // TODO: read meta EA
1971         }
1972
1973         if (AD_RSRC_OPEN(ad)) {
1974             if (ad_reso_fileno(ad) == -1)
1975                 return -1;
1976             struct stat st;
1977             if (fstat(ad_reso_fileno(ad), &st) == -1)
1978                 return -1;
1979             ad->ad_rlen = st.st_size;
1980         }
1981 #else
1982         if (AD_META_OPEN(ad)) {
1983             if (ad_data_fileno(ad) == -1)
1984                 return -1;
1985             // TODO: read meta EA
1986         }
1987         if (AD_RSRC_OPEN(ad)) {
1988             if (ad_reso_fileno(ad) == -1)
1989                 return -1;
1990             if (ad_header_read_osx(path, ad, NULL) < 0)
1991                 return -1;
1992         }
1993 #endif
1994         return ad->ad_ops->ad_header_read(path, ad, NULL);
1995         break;
1996     default:
1997         return -1;
1998         break;
1999     }
2000
2001 }
2002
2003 int ad_openat(struct adouble  *ad,
2004               int dirfd,  /* dir fd openat like */
2005               const char *path,
2006               int adflags, ...)
2007 {
2008     EC_INIT;
2009     int cwdfd = -1;
2010     va_list args;
2011     mode_t mode = 0;
2012
2013     if (dirfd != -1) {
2014         if (((cwdfd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0))
2015             EC_FAIL;
2016     }
2017
2018     va_start(args, adflags);
2019     if (adflags & ADFLAGS_CREATE)
2020         mode = (sizeof(mode_t) < sizeof(int) ? va_arg (args, int) : va_arg (args, mode_t));
2021     va_end(args);
2022
2023     EC_NEG1( ad_open(ad, path, adflags, mode) );
2024
2025     if (dirfd != -1) {
2026         if (fchdir(cwdfd) != 0) {
2027             AFP_PANIC("ad_openat: cant chdir back");
2028         }
2029     }
2030
2031 EC_CLEANUP:
2032     if (cwdfd != -1)
2033         close(cwdfd);
2034
2035     return ret;
2036 }
2037
2038 /* build a resource fork mode from the data fork mode:
2039  * remove X mode and extend header to RW if R or W (W if R for locking),
2040  */
2041 mode_t ad_hf_mode(mode_t mode)
2042 {
2043     mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
2044     /* fnctl lock need write access */
2045     if ((mode & S_IRUSR))
2046         mode |= S_IWUSR;
2047     if ((mode & S_IRGRP))
2048         mode |= S_IWGRP;
2049     if ((mode & S_IROTH))
2050         mode |= S_IWOTH;
2051
2052     /* if write mode set add read mode */
2053     if ((mode & S_IWUSR))
2054         mode |= S_IRUSR;
2055     if ((mode & S_IWGRP))
2056         mode |= S_IRGRP;
2057     if ((mode & S_IWOTH))
2058         mode |= S_IROTH;
2059
2060     return mode;
2061 }