]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
92ffc8852f4a0cf2095eae57ae507d14d6cb6934
[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         if (eid
411             && eid < ADEID_MAX
412             && off < sizeof(ad->ad_data)
413             && (off + len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
414             ad->ad_eid[ eid ].ade_off = off;
415             ad->ad_eid[ eid ].ade_len = len;
416         } else if (ret == 0) {
417             ret  = -11;
418             LOG(log_warning, logtype_ad, "parse_entries: bogus eid: %d", eid);
419         }
420     }
421
422     return ret;
423 }
424
425 /* this reads enough of the header so that we can figure out all of
426  * the entry lengths and offsets. once that's done, we just read/mmap
427  * the rest of the header in.
428  *
429  * NOTE: we're assuming that the resource fork is kept at the end of
430  *       the file. also, mmapping won't work for the hfs fs until it
431  *       understands how to mmap header files. */
432 static int ad_header_read(const char *path, struct adouble *ad, const struct stat *hst)
433 {
434     char                *buf = ad->ad_data;
435     uint16_t            nentries;
436     int                 len;
437     ssize_t             header_len;
438     struct stat         st;
439
440     /* read the header */
441     if ((header_len = adf_pread( ad->ad_mdp, buf, AD_DATASZ2, 0)) < 0) {
442         return -1;
443     }
444     if (header_len < AD_HEADER_LEN) {
445         errno = EIO;
446         return -1;
447     }
448
449     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
450     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
451     ad->ad_magic = ntohl( ad->ad_magic );
452     ad->ad_version = ntohl( ad->ad_version );
453
454     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
455         LOG(log_error, logtype_ad, "ad_open: can't parse AppleDouble header.");
456         errno = EIO;
457         return -1;
458     }
459
460     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
461     nentries = ntohs( nentries );
462
463     /* read in all the entry headers. if we have more than the
464      * maximum, just hope that the rfork is specified early on. */
465     len = nentries*AD_ENTRY_LEN;
466
467     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
468         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
469
470     buf += AD_HEADER_LEN;
471     if (len > header_len - AD_HEADER_LEN) {
472         LOG(log_error, logtype_ad, "ad_header_read: can't read entry info.");
473         errno = EIO;
474         return -1;
475     }
476
477     /* figure out all of the entry offsets and lengths. if we aren't
478      * able to read a resource fork entry, bail. */
479     nentries = len / AD_ENTRY_LEN;
480     if (parse_entries(ad, buf, nentries) != 0) {
481         LOG(log_warning, logtype_ad, "ad_header_read(%s): malformed AppleDouble",
482             path ? fullpathname(path) : "");
483     }
484     if (!ad_getentryoff(ad, ADEID_RFORK)
485         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
486         ) {
487         LOG(log_error, logtype_ad, "ad_header_read: problem with rfork entry offset.");
488         errno = EIO;
489         return -1;
490     }
491
492     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
493         LOG(log_error, logtype_ad, "ad_header_read: can't read in entries.");
494         errno = EIO;
495         return -1;
496     }
497
498     if (hst == NULL) {
499         hst = &st;
500         if (fstat(ad->ad_mdp->adf_fd, &st) < 0) {
501             return 1; /* fail silently */
502         }
503     }
504
505     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
506
507     return 0;
508 }
509
510 /* error here means it's not ad ._ adouble:osx file and thus we return 1 */
511 int ad_valid_header_osx(const char *path)
512 {
513     EC_INIT;
514     int fd = -1;
515     struct adouble      adosx;
516     char                *buf = &adosx.ad_data[0];
517     ssize_t             header_len;
518
519     LOG(log_debug, logtype_ad, "ad_valid_header_osx(\"%s\"): BEGIN", fullpathname(path));
520
521     EC_NEG1( fd = open(path, O_RDONLY) );
522
523     /* read the header */
524     EC_NEG1( header_len = read(fd, buf, AD_DATASZ_OSX) );
525
526     if (header_len < AD_HEADER_LEN)
527         EC_FAIL;
528
529     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
530     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
531     adosx.ad_magic = ntohl(adosx.ad_magic);
532     adosx.ad_version = ntohl(adosx.ad_version);
533
534     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
535         LOG(log_warning, logtype_ad, "ad_valid_header_osx(\"%s\"): not an adouble:osx file", fullpathname(path));
536         EC_FAIL;
537     }
538
539     if (strncmp(buf + ADEDOFF_FILLER, "Mac OS X", strlen("Mac OS X")) == 0)
540         /*
541          * It's a split fork created by OS X, it's not our "own" ._ file
542          * and thus not a valid header in this context.
543          * We allow enumeration and access.
544          */
545         EC_FAIL;
546
547 EC_CLEANUP:
548     LOG(log_debug, logtype_ad, "ad_valid_header_osx(\"%s\"): END: %d", fullpathname(path), ret);
549     if (fd != -1)
550         close(fd);
551     if (ret != 0)
552         return 1;
553     return 0;
554 }
555
556 /* Read an ._ file, only uses the resofork, finderinfo is taken from EA */
557 static int ad_header_read_osx(const char *path, struct adouble *ad, const struct stat *hst)
558 {
559     EC_INIT;
560     struct adouble      adosx;
561     char                *buf = &adosx.ad_data[0];
562     uint16_t            nentries;
563     int                 len;
564     ssize_t             header_len;
565     struct stat         st;
566
567     memset(buf, 0, sizeof(adosx.ad_data));
568
569     /* read the header */
570     EC_NEG1( header_len = adf_pread(ad->ad_rfp, buf, AD_DATASZ_OSX, 0) );
571
572     if (header_len < AD_HEADER_LEN) {
573         errno = EIO;
574         return -1;
575     }
576
577     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
578     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
579     adosx.ad_magic = ntohl(adosx.ad_magic);
580     adosx.ad_version = ntohl(adosx.ad_version);
581
582     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
583         LOG(log_error, logtype_ad, "ad_header_read_osx: can't parse AppleDouble header");
584         errno = EIO;
585         return -1;
586     }
587
588     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
589     nentries = ntohs(nentries);
590     len = nentries * AD_ENTRY_LEN;
591
592     if (len + AD_HEADER_LEN > sizeof(adosx.ad_data))
593         len = sizeof(adosx.ad_data) - AD_HEADER_LEN;
594
595     buf += AD_HEADER_LEN;
596     if (len > header_len - AD_HEADER_LEN) {
597         LOG(log_error, logtype_ad, "ad_header_read_osx: can't read entry info.");
598         errno = EIO;
599         return -1;
600     }
601
602     nentries = len / AD_ENTRY_LEN;
603     if (parse_entries(&adosx, buf, nentries) != 0) {
604         LOG(log_warning, logtype_ad, "ad_header_read(%s): malformed AppleDouble",
605             path ? fullpathname(path) : "");
606     }
607
608     if (ad_getentryoff(&adosx, ADEID_RFORK) == 0
609         || ad_getentryoff(&adosx, ADEID_RFORK) > sizeof(ad->ad_data)
610         || ad_getentryoff(&adosx, ADEID_RFORK) > header_len
611         ) {
612         LOG(log_error, logtype_ad, "ad_header_read_osx: problem with rfork entry offset.");
613         errno = EIO;
614         return -1;
615     }
616
617     if (hst == NULL) {
618         hst = &st;
619         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
620     }
621
622     ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(&adosx, ADEID_RFORK));
623     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
624
625 EC_CLEANUP:
626     EC_EXIT;
627 }
628
629 static int ad_header_read_ea(const char *path, struct adouble *ad, const struct stat *hst _U_)
630 {
631     EC_INIT;
632     uint16_t nentries;
633     int      len;
634     ssize_t  header_len;
635     char     *buf = ad->ad_data;
636
637     if (ad_meta_fileno(ad) != -1)
638         header_len = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_META, ad->ad_data, AD_DATASZ_EA);
639     else
640         header_len = sys_getxattr(path, AD_EA_META, ad->ad_data, AD_DATASZ_EA);
641     if (header_len < 1) {
642         LOG(log_debug, logtype_ad, "ad_header_read_ea: %s", strerror(errno));
643         EC_FAIL;
644     }
645
646     if (header_len < AD_DATASZ_EA) {
647         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): short metadata EA", fullpathname(path));
648         errno = EINVAL;
649         EC_FAIL;
650     }
651
652     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
653     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
654
655     ad->ad_magic = ntohl( ad->ad_magic );
656     ad->ad_version = ntohl( ad->ad_version );
657
658     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
659         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): wrong magic or version", fullpathname(path));
660         errno = EINVAL;
661         EC_FAIL;
662     }
663
664     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
665     nentries = ntohs( nentries );
666     if (nentries != ADEID_NUM_EA) {
667         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): invalid number of entries: %d", fullpathname(path), nentries);
668         errno = EINVAL;
669         EC_FAIL;
670     }
671
672     /* Now parse entries */
673     if (parse_entries(ad, buf + AD_HEADER_LEN, nentries)) {
674         LOG(log_warning, logtype_ad, "ad_header_read(%s): malformed AppleDouble",
675             path ? fullpathname(path) : "");
676     }
677
678     if (nentries != ADEID_NUM_EA
679         || !ad_entry(ad, ADEID_FINDERI)
680         || !ad_entry(ad, ADEID_COMMENT)
681         || !ad_entry(ad, ADEID_FILEDATESI)
682         || !ad_entry(ad, ADEID_AFPFILEI)
683         || !ad_entry(ad, ADEID_PRIVDEV)
684         || !ad_entry(ad, ADEID_PRIVINO)
685         || !ad_entry(ad, ADEID_PRIVSYN)
686         || !ad_entry(ad, ADEID_PRIVID)) {
687         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): invalid metadata EA", fullpathname(path));
688         errno = EINVAL;
689         EC_FAIL;
690     }
691
692 EC_CLEANUP:
693     if (ret != 0 && errno == EINVAL) {
694         become_root();
695         (void)sys_removexattr(path, AD_EA_META);
696         unbecome_root();
697         LOG(log_error, logtype_ad, "ad_header_read_ea(\"%s\"): deleted invalid metadata EA", fullpathname(path), nentries);
698         errno = ENOENT;
699     }
700     EC_EXIT;
701 }
702
703 /*!
704  * Takes a path to an AppleDouble file and creates the parrent .AppleDouble directory
705  *
706  * Example:
707  * path: "/path/.AppleDouble/file"
708  * => mkdir("/path/.AppleDouble/") (in ad_mkdir())
709  */
710 static int ad_mkrf(const char *path)
711 {
712     char *slash;
713     /*
714      * Probably .AppleDouble doesn't exist, try to mkdir it.
715      */
716     if (NULL == ( slash = strrchr( path, '/' )) ) {
717         return -1;
718     }
719     *slash = '\0';
720     errno = 0;
721     if ( ad_mkdir( path, 0777 ) < 0 ) {
722         return -1;
723     }
724     *slash = '/';
725     return 0;
726 }
727
728 #ifdef HAVE_EAFD
729 static int ad_mkrf_ea(const char *path _U_)
730 {
731     AFP_PANIC("ad_mkrf_ea: dont use");
732     return 0;
733 }
734 #endif
735
736 static int ad_mkrf_osx(const char *path _U_)
737 {
738     return 0;
739 }
740
741 /* ----------------
742    if we are root change path user/ group
743    It can be a native function for BSD cf. FAQ.Q10
744    path:  pathname to chown
745    stbuf: parent directory inode
746
747    use fstat and fchown or lchown with linux?
748 */
749 #define EMULATE_SUIDDIR
750
751 static int ad_chown(const char *path, struct stat *stbuf)
752 {
753     int ret = 0;
754 #ifdef EMULATE_SUIDDIR
755     uid_t id;
756
757     if (default_uid != (uid_t)-1) {
758         /* we are root (admin) */
759         id = (default_uid)?default_uid:stbuf->st_uid;
760         ret = lchown( path, id, stbuf->st_gid );
761     }
762 #endif
763     return ret;
764 }
765
766 #define DEFMASK 07700   /* be conservative */
767
768 /* ----------------
769    return access right and inode of path parent directory
770 */
771 static int ad_mode_st(const char *path, mode_t *mode, struct stat *stbuf)
772 {
773     if (*mode == 0) {
774         return -1;
775     }
776     if (ad_stat(path, stbuf) != 0) {
777         *mode &= DEFMASK;
778         return -1;
779     }
780     *mode &= stbuf->st_mode;
781     return 0;
782 }
783
784 /* --------------------------- */
785 static int ad_header_upgrade(struct adouble *ad _U_, const char *name _U_)
786 {
787     return 0;
788 }
789
790 static int ad_header_upgrade_ea(struct adouble *ad _U_, const char *name _U_)
791 {
792     AFP_PANIC("ad_header_upgrade_ea: dont use");
793     return 0;
794 }
795
796 /*!
797  * Error handling for adouble header(=metadata) file open error
798  *
799  * We're called because opening ADFLAGS_HF caused an error.
800  * 1. In case ad_open is called with ADFLAGS_NOHF the error is suppressed.
801  * 2. Open non-existent ressource fork, this will just result in first read return EOF
802  * 3. If ad_open was called with ADFLAGS_DF we may have opened the datafork and thus
803  *    ought to close it before returning with an error condition.
804  */
805 static int ad_error(struct adouble *ad, int adflags)
806 {
807     int err = errno;
808     if (adflags & ADFLAGS_NOHF) { /* 1 */
809         return 0;
810     }
811     if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_RF) && (errno == ENOENT)) /* 2 */
812         return 0;
813     if (adflags & (ADFLAGS_DF | ADFLAGS_SETSHRMD | ADFLAGS_CHECK_OF)) { /* 3 */
814         ad_close( ad, ADFLAGS_DF );
815         err = errno;
816     }
817     return -1 ;
818 }
819
820 /*!
821  * Map ADFLAGS to open() flags
822  *
823  * @param adfile   (r) the file you really want to open: ADFLAGS_DF or ADFLAGS_HF
824  * @param adflags  (r) flags from ad_open(..., adflags, ...)
825  * @returns            mapped flags suitable for calling open()
826  */
827 static int ad2openflags(const struct adouble *ad, int adfile, int adflags)
828 {
829     int oflags = 0;
830
831     if (adflags & ADFLAGS_RDWR)
832         oflags |= O_RDWR;
833     if (adflags & ADFLAGS_RDONLY) {
834         if (((adfile == ADFLAGS_DF || adfile == ADFLAGS_RF) && (adflags & ADFLAGS_SETSHRMD))
835             /* need rw access for locks */
836             || ((adfile == ADFLAGS_HF) && (ad->ad_vers == AD_VERSION2)))
837             /* need rw access for adouble file for the case:
838              1) openfork(data+meta:O_RDONLY), 2) openfork(reso(=meta):O_RDWR) */
839             oflags |= O_RDWR;
840         else
841             oflags |= O_RDONLY;
842     }
843     if (adflags & ADFLAGS_CREATE)
844         oflags |= O_CREAT;
845     if (adflags & ADFLAGS_EXCL)
846         oflags |= O_EXCL;
847     if (adflags & ADFLAGS_TRUNC)
848         oflags |= O_TRUNC;
849
850     if (!(ad->ad_options & ADVOL_FOLLO_SYML))
851         oflags |= O_NOFOLLOW;
852
853     return oflags;
854 }
855
856 static int ad_open_df(const char *path, int adflags, mode_t mode, struct adouble *ad)
857 {
858     EC_INIT;
859     struct stat st_dir;
860     int         oflags;
861     mode_t      admode;
862     int         st_invalid = -1;
863     ssize_t     lsz;
864
865     LOG(log_debug, logtype_ad,
866         "ad_open_df(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
867         fullpathname(path), adflags2logstr(adflags),
868         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
869         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
870         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
871
872     if (ad_data_fileno(ad) != -1) {
873         /* the file is already open, but we want write access: */
874         if ((adflags & ADFLAGS_RDWR)
875             /* and it was denied the first time: */
876             && (ad->ad_data_fork.adf_flags & O_RDONLY)) {
877                 errno = EACCES;
878                 return -1;
879             }
880         /* it's not new anymore */
881         ad->ad_data_fork.adf_flags &= ~( O_TRUNC | O_CREAT );
882         ad->ad_data_fork.adf_refcount++;
883         goto EC_CLEANUP;
884     }
885
886     oflags = ad2openflags(ad, ADFLAGS_DF, adflags);
887
888     admode = mode;
889     if ((adflags & ADFLAGS_CREATE)) {
890         st_invalid = ad_mode_st(path, &admode, &st_dir);
891         if ((ad->ad_options & ADVOL_UNIXPRIV))
892             admode = mode;
893     }
894
895     ad->ad_data_fork.adf_fd = open(path, oflags, admode);
896
897     if (ad->ad_data_fork.adf_fd == -1) {
898         switch (errno) {
899         case EACCES:
900         case EPERM:
901         case EROFS:
902             if ((adflags & ADFLAGS_SETSHRMD) && (adflags & ADFLAGS_RDONLY)) {
903                 oflags &= ~O_RDWR;
904                 oflags |= O_RDONLY;
905                 EC_NEG1( ad->ad_data_fork.adf_fd = open(path, oflags, admode) );
906                 break;
907             }
908             return -1;
909         case OPEN_NOFOLLOW_ERRNO:
910             ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
911             if ((lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN)) <= 0) {
912                 free(ad->ad_data_fork.adf_syml);
913                 EC_FAIL;
914             }
915             ad->ad_data_fork.adf_syml[lsz] = 0;
916             ad->ad_data_fork.adf_fd = AD_SYMLINK;
917             break;
918         default:
919             EC_FAIL;
920         }
921     }
922
923     if (!st_invalid)
924         ad_chown(path, &st_dir); /* just created, set owner if admin (root) */
925
926     ad->ad_data_fork.adf_flags = oflags;
927     adf_lock_init(&ad->ad_data_fork);
928     ad->ad_data_fork.adf_refcount++;
929
930 EC_CLEANUP:
931     LOG(log_debug, logtype_ad,
932         "ad_open_df(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
933         fullpathname(path), adflags2logstr(adflags), ret,
934         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
935         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
936         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
937     EC_EXIT;
938 }
939
940 static int ad_open_hf_v2(const char *path, int adflags, mode_t mode, struct adouble *ad)
941 {
942     EC_INIT;
943     struct stat st_dir;
944     struct stat st_meta;
945     struct stat *pst = NULL;
946     const char  *ad_p;
947     int         oflags, nocreatflags, opened = 0;
948     mode_t      admode;
949     int         st_invalid = -1;
950
951     LOG(log_debug, logtype_ad,
952         "ad_open_hf_v2(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
953         fullpathname(path), adflags2logstr(adflags),
954         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
955         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
956         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
957
958     if (ad_meta_fileno(ad) != -1) {
959         /* the file is already open, but we want write access: */
960         if ((adflags & ADFLAGS_RDWR) &&
961             /* and it was already denied: */
962             (ad->ad_mdp->adf_flags & O_RDONLY)) {
963             errno = EACCES;
964             EC_FAIL;
965         }
966         ad_refresh(path, ad);
967         /* it's not new anymore */
968         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
969         ad->ad_mdp->adf_refcount++;
970         goto EC_CLEANUP;
971     }
972
973     ad_p = ad->ad_ops->ad_path(path, adflags);
974     oflags = ad2openflags(ad, ADFLAGS_HF, adflags);
975     LOG(log_debug, logtype_ad,"ad_open_hf_v2(\"%s\"): open flags: %s",
976         fullpathname(path), openflags2logstr(oflags));
977     nocreatflags = oflags & ~(O_CREAT | O_EXCL);
978
979     ad_meta_fileno(ad) = open(ad_p, nocreatflags);
980
981     if (ad_meta_fileno(ad) != -1) {
982         ad->ad_mdp->adf_flags = nocreatflags;
983     } else {
984         switch (errno) {
985         case EACCES:
986         case EPERM:
987         case EROFS:
988             if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_SETSHRMD)) {
989                 nocreatflags &= ~O_RDWR;
990                 nocreatflags |= O_RDONLY;
991                 EC_NEG1( ad_meta_fileno(ad) = open(ad_p, nocreatflags) );
992                 ad->ad_mdp->adf_flags = nocreatflags;
993                 break;
994             }
995             EC_FAIL;
996         case ENOENT:
997             if (!(oflags & O_CREAT))
998                 EC_FAIL;
999             /*
1000              * We're expecting to create a new adouble header file here
1001              */
1002             LOG(log_debug, logtype_ad, "ad_open(\"%s\"): creating adouble file",
1003                 fullpathname(path));
1004             admode = mode;
1005             errno = 0;
1006             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1007             if ((ad->ad_options & ADVOL_UNIXPRIV))
1008                 admode = mode;
1009             admode = ad_hf_mode(admode);
1010             if (errno == ENOENT) {
1011                 EC_NEG1_LOG( ad->ad_ops->ad_mkrf(ad_p) );
1012                 admode = mode;
1013                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1014                 if ((ad->ad_options & ADVOL_UNIXPRIV))
1015                     admode = mode;
1016                 admode = ad_hf_mode(admode);
1017             }
1018
1019             /* retry with O_CREAT */
1020             EC_NEG1( ad_meta_fileno(ad) = open(ad_p, oflags, admode) );
1021             ad->ad_mdp->adf_flags = oflags;
1022             /* just created, set owner if admin owner (root) */
1023             if (!st_invalid)
1024                 ad_chown(ad_p, &st_dir);
1025             break;
1026         default:
1027             EC_FAIL;
1028         }
1029     }
1030
1031     /* Now we've got a new opened fd, we need to check that in the error case */
1032     opened = 1;
1033
1034     if (!(ad->ad_mdp->adf_flags & O_CREAT)) {
1035         /* check for 0 length files, treat them as new. */
1036         if (fstat(ad->ad_mdp->adf_fd, &st_meta) == 0) {
1037             if (st_meta.st_size == 0)
1038                 ad->ad_mdp->adf_flags |= O_TRUNC;
1039             else
1040                 /* we have valid data in st_meta stat structure, reused it in ad_header_read */
1041                 pst = &st_meta;
1042         }
1043     }
1044
1045     adf_lock_init(ad->ad_mdp);
1046     ad->ad_mdp->adf_refcount = 1;
1047
1048     if ((ad->ad_mdp->adf_flags & ( O_TRUNC | O_CREAT ))) {
1049         /* This is a new adouble header file, create it */
1050         EC_NEG1_LOG( new_ad_header(ad, path, pst, adflags) );
1051         ad_flush(ad);
1052     } else {
1053         /* Read the adouble header in and parse it.*/
1054         EC_NEG1_LOG( ad->ad_ops->ad_header_read(path, ad, pst) );
1055     }
1056
1057 EC_CLEANUP:
1058     if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
1059         close(ad_meta_fileno(ad));
1060         ad_meta_fileno(ad) = -1;
1061         ad->ad_mdp->adf_refcount = 0;
1062     }
1063     LOG(log_debug, logtype_ad,
1064         "ad_open_hf_v2(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1065         fullpathname(path), adflags2logstr(adflags), ret,
1066         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1067         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1068         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1069     EC_EXIT;
1070 }
1071
1072 static int ad_open_hf_ea(const char *path, int adflags, int mode, struct adouble *ad)
1073 {
1074     EC_INIT;
1075     int oflags;
1076     int opened = 0;
1077
1078     LOG(log_debug, logtype_ad,
1079         "ad_open_hf_ea(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1080         fullpathname(path), adflags2logstr(adflags),
1081         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1082         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1083         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1084
1085     oflags = ad2openflags(ad, ADFLAGS_DF, adflags) & ~(O_CREAT | O_TRUNC);
1086
1087     if (ad_meta_fileno(ad) == AD_SYMLINK)
1088         goto EC_CLEANUP;
1089
1090     if (ad_meta_fileno(ad) != -1) {
1091         /* the file is already open, but we want write access: */
1092         if ((oflags & O_RDWR) &&
1093             /* and it was already denied: */
1094             (ad->ad_mdp->adf_flags & O_RDONLY)) {
1095             LOG(log_error, logtype_ad, "ad_open_hf_ea(%s): rw request for ro file: %s",
1096                 fullpathname(path), strerror(errno));
1097             errno = EACCES;
1098             EC_FAIL;
1099         }
1100         /* it's not new anymore */
1101         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
1102     } else {
1103         if (oflags & O_RDWR) {
1104             /* Fo a RDONLY adouble we just use sys_lgetxattr instead if sys_fgetxattr */
1105             if (adflags & ADFLAGS_DIR)
1106                 /* For directories we open the directory RDONYL so we can later fchdir()  */
1107                 oflags = (oflags & ~O_RDWR) | O_RDONLY;
1108             LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): opening base file for meta adouble EA", path);
1109             EC_NEG1(ad_meta_fileno(ad) = open(path, oflags));
1110             opened = 1;
1111             ad->ad_mdp->adf_flags = oflags;
1112         }
1113     }
1114
1115     /* Read the adouble header in and parse it.*/
1116     if (ad->ad_ops->ad_header_read(path, ad, NULL) != 0) {
1117         if (!(adflags & ADFLAGS_CREATE)) {
1118             LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): can't read metadata EA", path);
1119             errno = ENOENT;
1120             EC_FAIL;
1121         }
1122         if ((adflags & ADFLAGS_CREATE) && (ad->ad_options & ADVOL_RO)) {
1123             errno = EROFS;
1124             EC_FAIL;
1125         }
1126
1127         LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): creating metadata EA", path);
1128
1129         /* It doesnt exist, EPERM or another error */
1130         if (!(errno == ENOATTR || errno == ENOENT)) {
1131             LOG(log_error, logtype_ad, "ad_open_hf_ea: unexpected: %s", strerror(errno));
1132             EC_FAIL;
1133         }
1134
1135         /* Create one */
1136         EC_NEG1_LOG(new_ad_header(ad, path, NULL, adflags));
1137         ad->ad_mdp->adf_flags |= O_CREAT; /* mark as just created */
1138         ad_flush(ad);
1139         LOG(log_debug, logtype_ad, "ad_open_hf_ea(\"%s\"): created metadata EA", path);
1140     }
1141
1142     if (ad_meta_fileno(ad) != -1)
1143         ad->ad_mdp->adf_refcount++;
1144     ad->ad_rlen = ad_reso_size(path, adflags, ad);
1145
1146 EC_CLEANUP:
1147     if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
1148         close(ad_meta_fileno(ad));
1149         ad_meta_fileno(ad) = -1;
1150         ad->ad_mdp->adf_refcount = 0;
1151     }
1152     LOG(log_debug, logtype_ad,
1153         "ad_open_hf_ea(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1154         fullpathname(path), adflags2logstr(adflags), ret,
1155         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1156         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1157         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1158         
1159     EC_EXIT;
1160 }
1161
1162 static int ad_open_hf(const char *path, int adflags, int mode, struct adouble *ad)
1163 {
1164     int ret = 0;
1165
1166     ad->ad_meta_refcount++;
1167
1168     switch (ad->ad_vers) {
1169     case AD_VERSION2:
1170         ret = ad_open_hf_v2(path, adflags, mode, ad);
1171         break;
1172     case AD_VERSION_EA:
1173         ret = ad_open_hf_ea(path, adflags, mode, ad);
1174         break;
1175     default:
1176         ret = -1;
1177         break;
1178     }
1179
1180     if (ret != 0) {
1181         ad->ad_meta_refcount--;
1182         ret = ad_error(ad, adflags);
1183     }
1184
1185     return ret;
1186 }
1187
1188 /*!
1189  * Get resofork length for adouble:ea, parameter 'ad' may be NULL
1190  */
1191 off_t ad_reso_size(const char *path, int adflags, struct adouble *ad)
1192 {
1193     EC_INIT;
1194     struct stat st;
1195     off_t rlen;
1196
1197     if (adflags & ADFLAGS_DIR)
1198         EC_FAIL;
1199
1200     LOG(log_debug, logtype_ad, "ad_reso_size(\"%s\"): BEGIN", path);
1201
1202 #ifdef HAVE_EAFD
1203     ssize_t easz;
1204
1205     if (ad && ad_reso_fileno(ad) != -1) {
1206         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
1207         rlen = st.st_size;
1208     } else if (ad && ad_meta_fileno(ad) != -1) {
1209         EC_NEG1( (rlen = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_RESO, NULL, 0)) );
1210     } else {
1211         EC_NEG1( (rlen = sys_lgetxattr(path, AD_EA_RESO, NULL, 0)) );
1212     }
1213
1214 #else
1215     const char *rfpath;
1216     EC_NULL_LOG( rfpath = ad_path_osx(path, adflags));
1217     EC_ZERO( lstat(rfpath, &st));
1218     if (st.st_size > ADEDOFF_RFORK_OSX)
1219         rlen = st.st_size - ADEDOFF_RFORK_OSX;
1220     else
1221         rlen = 0;
1222 #endif
1223
1224     LOG(log_debug, logtype_ad, "ad_reso_size(\"%s\"): size: %zd", path, rlen);
1225
1226 EC_CLEANUP:
1227     if (ret != 0)
1228         rlen = 0;
1229     return rlen;
1230 }
1231
1232 static int ad_open_rf_v2(const char *path, int adflags, int mode, struct adouble *ad)
1233 {
1234     EC_INIT;
1235
1236     /*
1237      * ad_open_hf_v2() does the work, but if it failed and adflags are ADFLAGS_NOHF | ADFLAGS_RF
1238      * ad_open_hf_v2() didn't give an error, but we're supposed to return a reso fork fd
1239      */
1240
1241     LOG(log_debug, logtype_ad, "ad_open_rf_v2(\"%s\"): BEGIN", fullpathname(path));
1242
1243     if (!AD_META_OPEN(ad) && !(adflags & (ADFLAGS_NORF | ADFLAGS_RDONLY)))
1244         EC_FAIL;
1245     if (AD_META_OPEN(ad))
1246         ad->ad_reso_refcount++;
1247
1248 EC_CLEANUP:
1249     LOG(log_debug, logtype_ad, "ad_open_rf_v2(\"%s\"): END: %d", fullpathname(path), ret);
1250     EC_EXIT;
1251 }
1252
1253 static int ad_open_rf_ea(const char *path, int adflags, int mode, struct adouble *ad)
1254 {
1255     EC_INIT;
1256     int oflags;
1257     int opened = 0;
1258     int closeflags = adflags & (ADFLAGS_DF | ADFLAGS_HF);
1259 #ifndef HAVE_EAFD
1260     const char *rfpath;
1261     struct stat st;
1262 #endif
1263
1264     LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): BEGIN", fullpathname(path));
1265
1266     oflags = ad2openflags(ad, ADFLAGS_RF, adflags) & ~O_CREAT;
1267
1268     if (ad_reso_fileno(ad) != -1) {
1269         /* the file is already open, but we want write access: */
1270         if ((oflags & O_RDWR)
1271             /* and it was already denied: */
1272             && (ad->ad_rfp->adf_flags & O_RDONLY)) {
1273             errno = EACCES;
1274             EC_FAIL;
1275         }
1276         ad->ad_rfp->adf_flags &= ~( O_TRUNC | O_CREAT );
1277         ad->ad_reso_refcount++;
1278         ad->ad_rfp->adf_refcount++;
1279         EC_NEG1_LOG( ad->ad_rlen = ad_reso_size(path, adflags, ad));
1280         goto EC_CLEANUP;
1281     }
1282 #ifdef HAVE_EAFD
1283     if (ad_meta_fileno(ad) < 0)
1284         EC_FAIL;
1285     if ((ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad), AD_EA_RESO, oflags)) == -1) {
1286         if (!(adflags & ADFLAGS_CREATE)) {
1287             switch (errno) {
1288             case EACCES:
1289             case EPERM:
1290             case EROFS:
1291                 if (!(adflags & ADFLAGS_RDONLY)) {
1292                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(path), strerror(errno));
1293                     EC_FAIL;
1294                 }
1295                 oflags &= ~O_RDWR;
1296                 oflags |= O_RDONLY;
1297                 if ((ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad), AD_EA_RESO, oflags)) == -1) {
1298                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(path), strerror(errno));
1299                     EC_FAIL;
1300                 }
1301                 break;
1302             case ENOENT:
1303                 EC_EXIT_STATUS(0);
1304             default:
1305                 LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(path), strerror(errno));
1306                 EC_FAIL;
1307             }
1308         } else {
1309             oflags |= O_CREAT;
1310             EC_NEG1_LOG( ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad),
1311                                                              AD_EA_RESO, oflags, 0666) );
1312         }
1313     }
1314 #else
1315     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags) );
1316     if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1317         if (!(adflags & ADFLAGS_CREATE)) {
1318             switch (errno) {
1319             case EACCES:
1320             case EPERM:
1321             case EROFS:
1322                 if (!(adflags & ADFLAGS_RDONLY)) {
1323                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(rfpath), strerror(errno));
1324                     EC_FAIL;
1325                 }
1326                 oflags &= ~O_RDWR;
1327                 oflags |= O_RDONLY;
1328                 if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1329                     LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(rfpath), strerror(errno));
1330                     EC_FAIL;
1331                 }
1332                 break;
1333             case ENOENT:
1334                 EC_EXIT_STATUS(0);
1335             default:
1336                 LOG(log_error, logtype_ad, "ad_open_rf_ea(\"%s\"): \"%s\"", fullpathname(rfpath), strerror(errno));
1337                 EC_FAIL;
1338             }
1339         } else {
1340             oflags |= O_CREAT;
1341             EC_NEG1_LOG( ad_reso_fileno(ad) = open(rfpath, oflags, mode) );
1342             LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): created adouble rfork: \"%s\"",
1343                 path, rfpath);
1344         }
1345     }
1346 #endif
1347     opened = 1;
1348     ad->ad_rfp->adf_refcount = 1;
1349     ad->ad_rfp->adf_flags = oflags;
1350     ad->ad_reso_refcount++;
1351
1352 #ifndef HAVE_EAFD
1353     EC_ZERO_LOG( fstat(ad_reso_fileno(ad), &st) );
1354     if (ad->ad_rfp->adf_flags & O_CREAT) {
1355         /* This is a new adouble header file, create it */
1356         LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): created adouble rfork, initializing: \"%s\"",
1357             path, rfpath);
1358         EC_NEG1_LOG( new_ad_header(ad, path, NULL, adflags) );
1359         LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): created adouble rfork, flushing: \"%s\"",
1360             path, rfpath);
1361         ad_flush(ad);
1362     } else {
1363         /* Read the adouble header */
1364         LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): reading adouble rfork: \"%s\"",
1365             path, rfpath);
1366         EC_NEG1_LOG( ad_header_read_osx(rfpath, ad, &st) );
1367     }
1368 #endif
1369
1370     ad->ad_rlen = ad_reso_size(path, adflags, ad);
1371
1372 EC_CLEANUP:
1373     if (ret != 0) {
1374         if (opened && (ad_reso_fileno(ad) != -1)) {
1375             close(ad_reso_fileno(ad));
1376             ad_reso_fileno(ad) = -1;
1377             ad->ad_reso_refcount--;
1378             ad->ad_rfp->adf_refcount = 0;
1379         }
1380         if (adflags & ADFLAGS_NORF) {
1381             ret = 0;
1382         } else {
1383             int err = errno;
1384             (void)ad_close(ad, closeflags);
1385             errno = err;
1386         }
1387         ad->ad_rlen = 0;
1388     }
1389
1390     LOG(log_debug, logtype_ad, "ad_open_rf(\"%s\"): END: %d", fullpathname(path), ret);
1391
1392     EC_EXIT;
1393 }
1394
1395 /*!
1396  * Open ressource fork
1397  */
1398 static int ad_open_rf(const char *path, int adflags, int mode, struct adouble *ad)
1399 {
1400     int ret = 0;
1401
1402     switch (ad->ad_vers) {
1403     case AD_VERSION2:
1404         ret = ad_open_rf_v2(path, adflags, mode, ad);
1405         break;
1406     case AD_VERSION_EA:
1407         ret = ad_open_rf_ea(path, adflags, mode, ad);
1408         break;
1409     default:
1410         ret = -1;
1411         break;
1412     }
1413
1414     return ret;
1415 }
1416
1417 /***********************************************************************************
1418  * API functions
1419  ********************************************************************************* */
1420
1421 off_t ad_getentryoff(const struct adouble *ad, int eid)
1422 {
1423     if (ad->ad_vers == AD_VERSION2)
1424         return ad->ad_eid[eid].ade_off;
1425
1426     switch (eid) {
1427     case ADEID_DFORK:
1428         return 0;
1429     case ADEID_RFORK:
1430 #ifdef HAVE_EAFD
1431         return 0;
1432 #else
1433         return ADEDOFF_RFORK_OSX;
1434 #endif
1435     default:
1436         return ad->ad_eid[eid].ade_off;
1437     }
1438     /* deadc0de */
1439     AFP_PANIC("What am I doing here?");
1440 }
1441
1442 const char *ad_path_ea( const char *path, int adflags _U_)
1443 {
1444     return path;
1445 }
1446
1447 const char *ad_path_osx(const char *path, int adflags _U_)
1448 {
1449     static char pathbuf[ MAXPATHLEN + 1];
1450     char    c, *slash, buf[MAXPATHLEN + 1];
1451
1452     if (!strcmp(path,".")) {
1453         /* fixme */
1454         getcwd(buf, MAXPATHLEN);
1455     }
1456     else {
1457         strlcpy(buf, path, MAXPATHLEN +1);
1458     }
1459     if (NULL != ( slash = strrchr( buf, '/' )) ) {
1460         c = *++slash;
1461         *slash = '\0';
1462         strlcpy( pathbuf, buf, MAXPATHLEN +1);
1463         *slash = c;
1464     } else {
1465         pathbuf[ 0 ] = '\0';
1466         slash = buf;
1467     }
1468     strlcat( pathbuf, "._", MAXPATHLEN  +1);
1469     strlcat( pathbuf, slash, MAXPATHLEN +1);
1470     return pathbuf;
1471 }
1472
1473 /*
1474  * Put the .AppleDouble where it needs to be:
1475  *
1476  *      /   a/.AppleDouble/b
1477  *  a/b
1478  *      \   b/.AppleDouble/.Parent
1479  *
1480  * FIXME: should do something for pathname > MAXPATHLEN
1481  */
1482 const char *ad_path( const char *path, int adflags)
1483 {
1484     static char pathbuf[ MAXPATHLEN + 1];
1485     const char *slash;
1486     size_t  l ;
1487
1488     if ( adflags & ADFLAGS_DIR ) {
1489         l = strlcpy( pathbuf, path, sizeof(pathbuf));
1490
1491         if ( l && l < MAXPATHLEN) {
1492             pathbuf[l++] = '/';
1493         }
1494         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
1495     } else {
1496         if (NULL != ( slash = strrchr( path, '/' )) ) {
1497             slash++;
1498             l = slash - path;
1499             /* XXX we must return NULL here and test in the caller */
1500             if (l > MAXPATHLEN)
1501                 l = MAXPATHLEN;
1502             memcpy( pathbuf, path, l);
1503         } else {
1504             l = 0;
1505             slash = path;
1506         }
1507         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
1508         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
1509     }
1510
1511     return( pathbuf );
1512 }
1513
1514 /* -------------------------
1515  * Support inherited protection modes for AppleDouble files.  The supplied
1516  * mode is ANDed with the parent directory's mask value in lieu of "umask",
1517  * and that value is returned.
1518  */
1519 char *ad_dir(const char *path)
1520 {
1521     static char     modebuf[ MAXPATHLEN + 1];
1522     char        *slash;
1523     /*
1524      * For a path with directories in it, remove the final component
1525      * (path or subdirectory name) to get the name we want to stat.
1526      * For a path which is just a filename, use "." instead.
1527      */
1528     slash = strrchr( path, '/' );
1529     if (slash) {
1530         size_t len;
1531
1532         len = slash - path;
1533         if (len >= MAXPATHLEN) {
1534             errno = ENAMETOOLONG;
1535             return NULL;  /* can't do it */
1536         }
1537         memcpy( modebuf, path, len );
1538         modebuf[len] = '\0';
1539         /* is last char a '/' ? */
1540         if (slash[1] == 0) {
1541             slash = modebuf+ len;
1542             /* remove them */
1543             while (modebuf < slash && slash[-1] == '/') {
1544                 --slash;
1545             }
1546             if (modebuf == slash) {
1547                 goto use_cur;
1548             }
1549             *slash = '\0';
1550             while (modebuf < slash && *slash != '/') {
1551                 --slash;
1552             }
1553             if (modebuf == slash) {
1554                 goto use_cur;
1555             }
1556             *slash = '\0';      /* remove pathname component */
1557         }
1558         return modebuf;
1559     }
1560 use_cur:
1561     modebuf[0] = '.';   /* use current directory */
1562     modebuf[1] = '\0';
1563     return modebuf;
1564 }
1565
1566 int ad_setfuid(const uid_t id)
1567 {
1568     default_uid = id;
1569     return 0;
1570 }
1571
1572 /* ---------------- */
1573 uid_t ad_getfuid(void)
1574 {
1575     return default_uid;
1576 }
1577
1578 /* ----------------
1579    stat path parent directory
1580 */
1581 int ad_stat(const char *path, struct stat *stbuf)
1582 {
1583     char *p;
1584
1585     p = ad_dir(path);
1586     if (!p)
1587         return -1;
1588     return stat( p, stbuf );
1589 }
1590
1591 /* ----------------
1592    return access right of path parent directory
1593 */
1594 int ad_mode( const char *path, mode_t mode)
1595 {
1596     struct stat     stbuf;
1597     ad_mode_st(path, &mode, &stbuf);
1598     return mode;
1599 }
1600
1601 /*
1602  * Use mkdir() with mode bits taken from ad_mode().
1603  */
1604 int ad_mkdir( const char *path, mode_t mode)
1605 {
1606     int ret;
1607     int st_invalid;
1608     struct stat stbuf;
1609
1610     LOG(log_debug, logtype_ad, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
1611         path, mode, getcwdpath());
1612
1613     st_invalid = ad_mode_st(path, &mode, &stbuf);
1614     ret = mkdir( path, mode );
1615     if (ret || st_invalid)
1616         return ret;
1617     ad_chown(path, &stbuf);
1618
1619     return ret;
1620 }
1621
1622 static void ad_init_func(struct adouble *ad)
1623 {
1624     switch (ad->ad_vers) {
1625     case AD_VERSION2:
1626         ad->ad_ops = &ad_adouble;
1627         ad->ad_rfp = &ad->ad_resource_fork;
1628         ad->ad_mdp = &ad->ad_resource_fork;
1629         break;
1630     case AD_VERSION_EA:
1631         ad->ad_ops = &ad_adouble_ea;
1632         ad->ad_rfp = &ad->ad_resource_fork;
1633         ad->ad_mdp = &ad->ad_data_fork;
1634         break;
1635     default:
1636         AFP_PANIC("ad_init: unknown AD version");
1637     }
1638
1639
1640     ad_data_fileno(ad) = -1;
1641     ad_reso_fileno(ad) = -1;
1642     ad_meta_fileno(ad) = -1;
1643     ad->ad_refcount = 1;
1644     ad->ad_rlen = 0;
1645     return;
1646 }
1647
1648 void ad_init_old(struct adouble *ad, int flags, int options)
1649 {
1650     memset(ad, 0, sizeof(struct adouble));
1651     ad->ad_vers = flags;
1652     ad->ad_options = options;
1653     ad_init_func(ad);
1654 }
1655
1656 void ad_init(struct adouble *ad, const struct vol * restrict vol)
1657 {
1658     memset(ad, 0, sizeof(struct adouble));
1659     ad->ad_vers = vol->v_adouble;
1660     ad->ad_options = vol->v_ad_options;
1661     ad_init_func(ad);
1662 }
1663
1664 /*!
1665  * Open data-, metadata(header)- or ressource fork
1666  *
1667  * ad_open(struct adouble *ad, const char *path, int adflags, int flags)
1668  * ad_open(struct adouble *ad, const char *path, int adflags, int flags, mode_t mode)
1669  *
1670  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1671  * @code
1672  *      struct adoube ad;
1673  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1674  * @endcode
1675  *
1676  * Open a files data fork, metadata fork or ressource fork.
1677  *
1678  * @param ad        (rw) pointer to struct adouble
1679  * @param path      (r)  Path to file or directory
1680  * @param adflags   (r)  Flags specifying which fork to open, can be or'd:
1681  *                         ADFLAGS_DF:        open data fork
1682  *                         ADFLAGS_RF:        open ressource fork
1683  *                         ADFLAGS_HF:        open header (metadata) file
1684  *                         ADFLAGS_NOHF:      it's not an error if header file couldn't be opened
1685  *                         ADFLAGS_NORF:      it's not an error if reso fork couldn't be opened
1686  *                         ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags
1687  *
1688  *                       Access mode for the forks:
1689  *                         ADFLAGS_RDONLY:    open read only
1690  *                         ADFLAGS_RDWR:      open read write
1691  *
1692  *                       Creation flags:
1693  *                         ADFLAGS_CREATE:    create if not existing
1694  *                         ADFLAGS_TRUNC:     truncate
1695  *
1696  *                       Special flags:
1697  *                         ADFLAGS_CHECK_OF:  check for open forks from us and other afpd's
1698  *                         ADFLAGS_SETSHRMD:  this adouble struct will be used to set sharemode locks.
1699  *                                            This basically results in the files being opened RW instead of RDONLY.
1700  * @param mode      (r)  mode used with O_CREATE
1701  *
1702  * The open mode flags (rw vs ro) have to take into account all the following requirements:
1703  * - we remember open fds for files because me must avoid a single close releasing fcntl locks for other
1704  *   fds of the same file
1705  *
1706  * @returns 0 on success, any other value indicates an error
1707  */
1708 int ad_open(struct adouble *ad, const char *path, int adflags, ...)
1709 {
1710     EC_INIT;
1711     va_list args;
1712     mode_t mode = 0;
1713
1714     LOG(log_debug, logtype_ad,
1715         "ad_open(\"%s\", %s): BEGIN {d: %d, m: %d, r: %d}"
1716         "[dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1717         fullpathname(path), adflags2logstr(adflags),
1718         ad->ad_data_refcount, ad->ad_meta_refcount, ad->ad_reso_refcount,
1719         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1720         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1721         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1722
1723     if (adflags & ADFLAGS_CHECK_OF)
1724         /* Checking for open forks requires sharemode lock support (ie RDWR instead of RDONLY) */
1725         adflags |= ADFLAGS_SETSHRMD;
1726
1727     if (adflags & ADFLAGS_SETSHRMD)
1728         /* sharemode locks are stored in the data fork */
1729         adflags |= ADFLAGS_DF;
1730
1731     if (ad->ad_vers == AD_VERSION2) {
1732         if (adflags & ADFLAGS_RF)
1733             adflags |= ADFLAGS_HF;
1734         if (adflags & ADFLAGS_NORF)
1735             adflags |= ADFLAGS_NOHF;
1736     }
1737
1738     if (ad->ad_inited != AD_INITED) {
1739         ad->ad_adflags = adflags;
1740         ad->ad_inited = AD_INITED;
1741     } else {
1742         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1743         if (ad->ad_resource_fork.adf_refcount > 0)
1744             ad->ad_open_forks |= ATTRBIT_ROPEN;
1745     }
1746
1747     va_start(args, adflags);
1748     if (adflags & ADFLAGS_CREATE)
1749         mode = (sizeof(mode_t) < sizeof(int) ? va_arg (args, int) : va_arg (args, mode_t));
1750     va_end(args);
1751
1752     if (adflags & ADFLAGS_DF) {
1753         ad->ad_data_refcount++;
1754         if (ad_open_df(path, adflags, mode, ad) != 0) {
1755             ad->ad_data_refcount--;
1756             EC_FAIL;
1757         }
1758     }
1759
1760     if (adflags & ADFLAGS_HF) {
1761         if (ad_open_hf(path, adflags, mode, ad) != 0) {
1762             EC_FAIL;
1763         }
1764     }
1765
1766     if (adflags & ADFLAGS_RF) {
1767         if (ad_open_rf(path, adflags, mode, ad) != 0) {
1768             EC_FAIL;
1769         }
1770     }
1771
1772     if (adflags & ADFLAGS_CHECK_OF) {
1773         ad->ad_open_forks |= ad_openforks(ad, ad->ad_open_forks);
1774     }
1775
1776 EC_CLEANUP:
1777     LOG(log_debug, logtype_ad,
1778         "ad_open(\"%s\"): END: %d {d: %d, m: %d, r: %d}"
1779         "[dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1780         fullpathname(path), ret,
1781         ad->ad_data_refcount, ad->ad_meta_refcount, ad->ad_reso_refcount,
1782         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1783         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1784         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1785
1786     EC_EXIT;
1787 }
1788
1789 /*!
1790  * @brief open metadata, possibly as root
1791  *
1792  * Return only metadata but try very hard ie at first try as user, then try as root.
1793  *
1794  * @param name  name of file/dir
1795  * @param flags ADFLAGS_DIR: name is a directory \n
1796  *              ADFLAGS_CHECK_OF: test if name is open by us or another afpd process
1797  *
1798  * @param adp   pointer to struct adouble
1799  */
1800 int ad_metadata(const char *name, int flags, struct adouble *adp)
1801 {
1802     int   ret, err, oflags;
1803
1804     /* Sanitize flags */
1805     oflags = (flags & (ADFLAGS_CHECK_OF | ADFLAGS_DIR)) | ADFLAGS_HF | ADFLAGS_RDONLY;    
1806
1807     if ((ret = ad_open(adp, name, oflags)) < 0 && errno == EACCES) {
1808         become_root();
1809         ret = ad_open(adp, name, oflags);
1810         unbecome_root();
1811         err = errno;
1812         errno = err;
1813     }
1814
1815     return ret;
1816 }
1817
1818 /*
1819  * @brief openat like wrapper for ad_metadata
1820  */
1821 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1822 {
1823     int ret = 0;
1824     int cwdfd = -1;
1825
1826     if (dirfd != -1) {
1827         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1828             ret = -1;
1829             goto exit;
1830         }
1831     }
1832
1833     if (ad_metadata(name, flags, adp) < 0) {
1834         ret = -1;
1835         goto exit;
1836     }
1837
1838     if (dirfd != -1) {
1839
1840         if (fchdir(cwdfd) != 0) {
1841             LOG(log_error, logtype_ad, "ad_openat: cant chdir back, exiting");
1842             exit(EXITERR_SYS);
1843         }
1844     }
1845
1846 exit:
1847     if (cwdfd != -1)
1848         close(cwdfd);
1849
1850     return ret;
1851
1852 }
1853
1854 int ad_refresh(const char *path, struct adouble *ad)
1855 {
1856     switch (ad->ad_vers) {
1857     case AD_VERSION2:
1858         if (ad_meta_fileno(ad) == -1)
1859             return -1;
1860         return ad->ad_ops->ad_header_read(NULL, ad, NULL);
1861         break;
1862     case AD_VERSION_EA:
1863 #ifdef HAVE_EAFD
1864         if (AD_META_OPEN(ad)) {
1865             if (ad_data_fileno(ad) == -1)
1866                 return -1;
1867             // TODO: read meta EA
1868         }
1869
1870         if (AD_RSRC_OPEN(ad)) {
1871             if (ad_reso_fileno(ad) == -1)
1872                 return -1;
1873             struct stat st;
1874             if (fstat(ad_reso_fileno(ad), &st) == -1)
1875                 return -1;
1876             ad->ad_rlen = st.st_size;
1877         }
1878 #else
1879         if (AD_META_OPEN(ad)) {
1880             if (ad_data_fileno(ad) == -1)
1881                 return -1;
1882             // TODO: read meta EA
1883         }
1884         if (AD_RSRC_OPEN(ad)) {
1885             if (ad_reso_fileno(ad) == -1)
1886                 return -1;
1887             if (ad_header_read_osx(path, ad, NULL) < 0)
1888                 return -1;
1889         }
1890 #endif
1891         return ad->ad_ops->ad_header_read(path, ad, NULL);
1892         break;
1893     default:
1894         return -1;
1895         break;
1896     }
1897
1898 }
1899
1900 int ad_openat(struct adouble  *ad,
1901               int dirfd,  /* dir fd openat like */
1902               const char *path,
1903               int adflags, ...)
1904 {
1905     EC_INIT;
1906     int cwdfd = -1;
1907     va_list args;
1908     mode_t mode = 0;
1909
1910     if (dirfd != -1) {
1911         if (((cwdfd = open(".", O_RDONLY)) == -1) || (fchdir(dirfd) != 0))
1912             EC_FAIL;
1913     }
1914
1915     va_start(args, adflags);
1916     if (adflags & ADFLAGS_CREATE)
1917         mode = (sizeof(mode_t) < sizeof(int) ? va_arg (args, int) : va_arg (args, mode_t));
1918     va_end(args);
1919
1920     EC_NEG1( ad_open(ad, path, adflags, mode) );
1921
1922     if (dirfd != -1) {
1923         if (fchdir(cwdfd) != 0) {
1924             AFP_PANIC("ad_openat: cant chdir back");
1925         }
1926     }
1927
1928 EC_CLEANUP:
1929     if (cwdfd != -1)
1930         close(cwdfd);
1931
1932     return ret;
1933 }
1934
1935 /* build a resource fork mode from the data fork mode:
1936  * remove X mode and extend header to RW if R or W (W if R for locking),
1937  */
1938 mode_t ad_hf_mode(mode_t mode)
1939 {
1940     mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
1941     /* fnctl lock need write access */
1942     if ((mode & S_IRUSR))
1943         mode |= S_IWUSR;
1944     if ((mode & S_IRGRP))
1945         mode |= S_IWGRP;
1946     if ((mode & S_IROTH))
1947         mode |= S_IWOTH;
1948
1949     /* if write mode set add read mode */
1950     if ((mode & S_IWUSR))
1951         mode |= S_IRUSR;
1952     if ((mode & S_IWGRP))
1953         mode |= S_IRGRP;
1954     if ((mode & S_IWOTH))
1955         mode |= S_IROTH;
1956
1957     return mode;
1958 }