]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Datafork is implicitly openend in metadata open
[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/ea.h>
49 #include <atalk/bstrlib.h>
50 #include <atalk/bstradd.h>
51 #include <atalk/compat.h>
52 #include <atalk/errchk.h>
53 #include <atalk/volume.h>
54
55 #include "ad_lock.h"
56
57 #define ADEDOFF_MAGIC        (0)
58 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
59 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
60 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
61
62 /* initial lengths of some of the fields */
63 #define ADEDLEN_INIT     0
64
65 /* i stick things in a slightly different order than their eid order in
66  * case i ever want to separate RootInfo behaviour from the rest of the
67  * stuff. */
68
69 /* ad:v2 */
70 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
71 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
72 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
73 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
74 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
75 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
76 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
77 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
78 #define ADEDOFF_PRIVDEV      (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
79 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
80 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
81 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
82 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
83
84 /* ad:ea */
85 #define ADEDOFF_FINDERI_EA   (AD_HEADER_LEN + ADEID_NUM_EA * AD_ENTRY_LEN)
86 #define ADEDOFF_COMMENT_EA   (ADEDOFF_FINDERI_EA + ADEDLEN_FINDERI)
87 #define ADEDOFF_FILEDATESI_EA (ADEDOFF_COMMENT_EA + ADEDLEN_COMMENT)
88 #define ADEDOFF_AFPFILEI_EA  (ADEDOFF_FILEDATESI_EA + ADEDLEN_FILEDATESI)
89
90 /* this is to prevent changing timezones from causing problems with
91    localtime volumes. the screw-up is 30 years. we use a delta of 5 years */
92 #define TIMEWARP_DELTA 157680000
93
94 struct entry {
95     uint32_t id, offset, len;
96 };
97
98 /* --------------------------- */
99 static uid_t default_uid = -1;
100
101 /* Forward declarations */
102 static int ad_mkrf(const char *path);
103 static int ad_header_read(const char *path, struct adouble *ad, struct stat *hst);
104 static int ad_header_upgrade(struct adouble *ad, const char *name);
105
106 static int ad_mkrf_ea(const char *path);
107 static int ad_header_read_ea(const char *path, struct adouble *ad, struct stat *hst);
108 static int ad_header_upgrade_ea(struct adouble *ad, const char *name);
109 static int ad_reso_size(const char *path, int adflags, struct adouble *ad);
110 static int ad_mkrf_osx(const char *path);
111
112
113 static struct adouble_fops ad_adouble = {
114     &ad_path,
115     &ad_mkrf,
116     &ad_rebuild_adouble_header,
117     &ad_header_read,
118     &ad_header_upgrade,
119 };
120
121 static struct adouble_fops ad_adouble_ea = {
122 #ifdef HAVE_EAFD
123     &ad_path_ea,
124     &ad_mkrf_ea,
125 #else
126     &ad_path_osx,
127     &ad_mkrf_osx,
128 #endif
129     &ad_rebuild_adouble_header,
130     &ad_header_read_ea,
131     &ad_header_upgrade_ea,
132 };
133
134 static struct adouble_fops ad_osx = {
135     &ad_path_osx,
136     &ad_mkrf_osx,
137     &ad_rebuild_adouble_header,
138     &ad_header_read,
139     &ad_header_upgrade,
140 };
141
142 static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
143     {ADEID_NAME,        ADEDOFF_NAME_V2,     ADEDLEN_INIT},
144     {ADEID_COMMENT,     ADEDOFF_COMMENT_V2,  ADEDLEN_INIT},
145     {ADEID_FILEDATESI,  ADEDOFF_FILEDATESI,  ADEDLEN_FILEDATESI},
146     {ADEID_FINDERI,     ADEDOFF_FINDERI_V2,  ADEDLEN_FINDERI},
147     {ADEID_DID,         ADEDOFF_DID,         ADEDLEN_DID},
148     {ADEID_AFPFILEI,    ADEDOFF_AFPFILEI,    ADEDLEN_AFPFILEI},
149     {ADEID_SHORTNAME,   ADEDOFF_SHORTNAME,   ADEDLEN_INIT},
150     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
151     {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV,     ADEDLEN_INIT},
152     {ADEID_PRIVINO,     ADEDOFF_PRIVINO,     ADEDLEN_INIT},
153     {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN,     ADEDLEN_INIT},
154     {ADEID_PRIVID,      ADEDOFF_PRIVID,      ADEDLEN_INIT},
155     {ADEID_RFORK,       ADEDOFF_RFORK_V2,    ADEDLEN_INIT},
156     {0, 0, 0}
157 };
158
159 /* Using Extended Attributes */
160 static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
161     {ADEID_FINDERI,    ADEDOFF_FINDERI_EA,    ADEDLEN_FINDERI},
162     {ADEID_COMMENT,    ADEDOFF_COMMENT_EA,    ADEDLEN_INIT},
163     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_EA, ADEDLEN_FILEDATESI},
164     {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_EA,   ADEDLEN_AFPFILEI},
165     {ADEID_PRIVID,     ADEDOFF_PRIVID,        ADEDLEN_INIT},
166     {0, 0, 0}
167 };
168
169 /* fallback for EAs */
170 static const struct entry entry_order_osx[ADEID_NUM_OSX +1] = {
171     {ADEID_FINDERI, ADEDOFF_FINDERI_OSX, ADEDLEN_FINDERI},
172     {ADEID_RFORK, ADEDOFF_RFORK_OSX, ADEDLEN_INIT},
173     {0, 0, 0}
174 };
175
176 #define ADFLAGS2LOGSTRBUFSIZ 128
177 const char *adflags2logstr(int adflags)
178 {
179     int first = 1;
180     static char buf[ADFLAGS2LOGSTRBUFSIZ];
181
182     buf[0] = 0;
183
184     if (adflags & ADFLAGS_DF) {
185         strlcat(buf, "DF", ADFLAGS2LOGSTRBUFSIZ);
186         first = 0;
187     }
188     if (adflags & ADFLAGS_RF) {
189         if (!first)
190             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
191         strlcat(buf, "RF", ADFLAGS2LOGSTRBUFSIZ);
192         first = 0;
193     }
194     if (adflags & ADFLAGS_HF) {
195         if (!first)
196             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
197         strlcat(buf, "HF", ADFLAGS2LOGSTRBUFSIZ);
198         first = 0;
199     }
200     if (adflags & ADFLAGS_NOHF) {
201         if (!first)
202             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
203         strlcat(buf, "NOHF", ADFLAGS2LOGSTRBUFSIZ);
204         first = 0;
205     }
206     if (adflags & ADFLAGS_DIR) {
207         if (!first)
208             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
209         strlcat(buf, "DIR", ADFLAGS2LOGSTRBUFSIZ);
210         first = 0;
211     }
212     if (adflags & ADFLAGS_CHECK_OF) {
213         if (!first)
214             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
215         strlcat(buf, "OF", ADFLAGS2LOGSTRBUFSIZ);
216         first = 0;
217     }
218     if (adflags & ADFLAGS_RDWR) {
219         if (!first)
220             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
221         strlcat(buf, "O_RDWR", ADFLAGS2LOGSTRBUFSIZ);
222         first = 0;
223     }
224     if (adflags & ADFLAGS_RDONLY) {
225         if (!first)
226             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
227         strlcat(buf, "O_RDONLY", ADFLAGS2LOGSTRBUFSIZ);
228         first = 0;
229     }
230     if (adflags & ADFLAGS_CREATE) {
231         if (!first)
232             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
233         strlcat(buf, "O_CREAT", ADFLAGS2LOGSTRBUFSIZ);
234         first = 0;
235     }
236     if (adflags & ADFLAGS_EXCL) {
237         if (!first)
238             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
239         strlcat(buf, "O_EXCL", ADFLAGS2LOGSTRBUFSIZ);
240         first = 0;
241     }
242     if (adflags & ADFLAGS_TRUNC) {
243         if (!first)
244             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
245         strlcat(buf, "O_TRUNC", ADFLAGS2LOGSTRBUFSIZ);
246         first = 0;
247     }
248
249     return buf;
250 }
251
252 static uint32_t get_eid(uint32_t eid)
253 {
254     if (eid <= 15)
255         return eid;
256     if (eid == AD_DEV)
257         return ADEID_PRIVDEV;
258     if (eid == AD_INO)
259         return ADEID_PRIVINO;
260     if (eid == AD_SYN)
261         return ADEID_PRIVSYN;
262     if (eid == AD_ID)
263         return ADEID_PRIVID;
264
265     return 0;
266 }
267
268 /* ----------------------------------- */
269 static int new_ad_header(struct adouble *ad, const char *path, struct stat *stp, int adflags)
270 {
271     const struct entry  *eid;
272     uint16_t            ashort;
273     struct stat         st;
274
275     LOG(log_debug, logtype_default, "new_ad_header(\"%s\")", path);
276
277     if (stp == NULL) {
278         stp = &st;
279         if (lstat(path, &st) != 0)
280             return -1;
281     }
282
283     ad->ad_magic = AD_MAGIC;
284     ad->ad_version = ad->ad_vers & 0x0f0000;
285     if (!ad->ad_version) {
286         ad->ad_version = AD_VERSION;
287     }
288
289     memset(ad->ad_data, 0, sizeof(ad->ad_data));
290
291     if (ad->ad_vers == AD_VERSION2)
292         eid = entry_order2;
293     else if (ad->ad_vers == AD_VERSION_EA)
294         eid = entry_order_ea;
295     else if (ad->ad_vers == AD_VERSION2_OSX)
296         eid = entry_order_osx;
297     else {
298         return -1;
299     }
300
301     while (eid->id) {
302         ad->ad_eid[eid->id].ade_off = eid->offset;
303         ad->ad_eid[eid->id].ade_len = eid->len;
304         eid++;
305     }
306
307     /* put something sane in the directory finderinfo */
308     if (ad->ad_vers != AD_VERSION2_OSX) {
309         if ((adflags & ADFLAGS_DIR)) {
310             /* set default view */
311             ashort = htons(FINDERINFO_CLOSEDVIEW);
312             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
313         } else {
314             /* set default creator/type fields */
315             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
316             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
317         }
318
319         /* make things invisible */
320         if ((ad->ad_options & ADVOL_INVDOTS)
321             && (*path == '.')
322             && !((adflags & ADFLAGS_DIR) && (path[1] == 0))
323             ) {
324             ashort = htons(ATTRBIT_INVISIBLE);
325             ad_setattr(ad, ashort);
326             ashort = htons(FINDERINFO_INVISIBLE);
327             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
328         }
329
330         /* put something sane in the date fields */
331         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, stp->st_mtime);
332         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, stp->st_mtime);
333         ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, stp->st_mtime);
334         ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
335     }
336     return 0;
337 }
338
339 /* -------------------------------------
340    read in the entries
341 */
342 static void parse_entries(struct adouble *ad, char *buf, uint16_t nentries)
343 {
344     uint32_t   eid, len, off;
345     int        warning = 0;
346
347     /* now, read in the entry bits */
348     for (; nentries > 0; nentries-- ) {
349         memcpy(&eid, buf, sizeof( eid ));
350         eid = get_eid(ntohl(eid));
351         buf += sizeof( eid );
352         memcpy(&off, buf, sizeof( off ));
353         off = ntohl( off );
354         buf += sizeof( off );
355         memcpy(&len, buf, sizeof( len ));
356         len = ntohl( len );
357         buf += sizeof( len );
358
359         if (eid
360             && eid < ADEID_MAX
361             && off < sizeof(ad->ad_data)
362             && (off + len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
363             ad->ad_eid[ eid ].ade_off = off;
364             ad->ad_eid[ eid ].ade_len = len;
365         } else if (!warning) {
366             warning = 1;
367             LOG(log_warning, logtype_default, "parse_entries: bogus eid: %d", eid);
368         }
369     }
370 }
371
372 /* this reads enough of the header so that we can figure out all of
373  * the entry lengths and offsets. once that's done, we just read/mmap
374  * the rest of the header in.
375  *
376  * NOTE: we're assuming that the resource fork is kept at the end of
377  *       the file. also, mmapping won't work for the hfs fs until it
378  *       understands how to mmap header files. */
379 static int ad_header_read(const char *path _U_, struct adouble *ad, struct stat *hst)
380 {
381     char                *buf = ad->ad_data;
382     uint16_t            nentries;
383     int                 len;
384     ssize_t             header_len;
385     struct stat         st;
386
387     /* read the header */
388     if ((header_len = adf_pread( ad->ad_mdp, buf, AD_DATASZ, 0)) < 0) {
389         return -1;
390     }
391     if (header_len < AD_HEADER_LEN) {
392         errno = EIO;
393         return -1;
394     }
395
396     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
397     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
398     ad->ad_magic = ntohl( ad->ad_magic );
399     ad->ad_version = ntohl( ad->ad_version );
400
401     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
402         LOG(log_error, logtype_default, "ad_open: can't parse AppleDouble header.");
403         errno = EIO;
404         return -1;
405     }
406
407     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
408     nentries = ntohs( nentries );
409
410     /* read in all the entry headers. if we have more than the
411      * maximum, just hope that the rfork is specified early on. */
412     len = nentries*AD_ENTRY_LEN;
413
414     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
415         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
416
417     buf += AD_HEADER_LEN;
418     if (len > header_len - AD_HEADER_LEN) {
419         LOG(log_error, logtype_default, "ad_header_read: can't read entry info.");
420         errno = EIO;
421         return -1;
422     }
423
424     /* figure out all of the entry offsets and lengths. if we aren't
425      * able to read a resource fork entry, bail. */
426     nentries = len / AD_ENTRY_LEN;
427     parse_entries(ad, buf, nentries);
428     if (!ad_getentryoff(ad, ADEID_RFORK)
429         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
430         ) {
431         LOG(log_error, logtype_default, "ad_header_read: problem with rfork entry offset.");
432         errno = EIO;
433         return -1;
434     }
435
436     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
437         LOG(log_error, logtype_default, "ad_header_read: can't read in entries.");
438         errno = EIO;
439         return -1;
440     }
441
442     if (hst == NULL) {
443         hst = &st;
444         if (fstat(ad->ad_mdp->adf_fd, &st) < 0) {
445             return 1; /* fail silently */
446         }
447     }
448
449     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
450
451     return 0;
452 }
453
454 /* Read an ._ file, only uses the resofork, finderinfo is taken from EA */
455 static int ad_header_read_osx(const char *path _U_, struct adouble *ad, struct stat *hst)
456 {
457     EC_INIT;
458     struct adouble      adosx;
459     char                *buf = &adosx.ad_data[0];
460     uint16_t            nentries;
461     int                 len;
462     ssize_t             header_len;
463     struct stat         st;
464
465     memset(buf, 0, sizeof(adosx.ad_data));
466
467     /* read the header */
468     EC_NEG1( header_len = adf_pread(ad->ad_rfp, buf, AD_DATASZ_OSX, 0) );
469
470     if (header_len < AD_HEADER_LEN) {
471         errno = EIO;
472         return -1;
473     }
474
475     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
476     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
477     adosx.ad_magic = ntohl(adosx.ad_magic);
478     adosx.ad_version = ntohl(adosx.ad_version);
479
480     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
481         LOG(log_error, logtype_afpd, "ad_header_read_osx: can't parse AppleDouble header");
482         errno = EIO;
483         return -1;
484     }
485
486     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
487     nentries = ntohs(nentries);
488     len = nentries * AD_ENTRY_LEN;
489
490     if (len + AD_HEADER_LEN > sizeof(adosx.ad_data))
491         len = sizeof(adosx.ad_data) - AD_HEADER_LEN;
492
493     buf += AD_HEADER_LEN;
494     if (len > header_len - AD_HEADER_LEN) {
495         LOG(log_error, logtype_afpd, "ad_header_read_osx: can't read entry info.");
496         errno = EIO;
497         return -1;
498     }
499
500     nentries = len / AD_ENTRY_LEN;
501     parse_entries(&adosx, buf, nentries);
502
503     if (ad_getentryoff(&adosx, ADEID_RFORK) == 0
504         || ad_getentryoff(&adosx, ADEID_RFORK) > sizeof(ad->ad_data)
505         || ad_getentryoff(&adosx, ADEID_RFORK) > header_len
506         ) {
507         LOG(log_error, logtype_afpd, "ad_header_read_osx: problem with rfork entry offset.");
508         errno = EIO;
509         return -1;
510     }
511
512     if (hst == NULL) {
513         hst = &st;
514         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
515     }
516
517     ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(&adosx, ADEID_RFORK));
518     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
519
520 EC_CLEANUP:
521     EC_EXIT;
522 }
523
524 static int ad_header_read_ea(const char *path, struct adouble *ad, struct stat *hst _U_)
525 {
526     uint16_t nentries;
527     int      len;
528     ssize_t  header_len;
529     char     *buf = ad->ad_data;
530
531     /* read the header */
532     if ((ad_meta_fileno(ad) == -1)
533         && (ad->ad_adflags & ADFLAGS_RDWR)) {
534         LOG(log_error, logtype_default, "ad_header_read_ea: need filedescriptor for rw access");
535         return -1;
536     }
537
538     if (ad_meta_fileno(ad) != -1)
539         header_len = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_META, ad->ad_data, AD_DATASZ_EA);
540     else
541         header_len = sys_lgetxattr(path, AD_EA_META, ad->ad_data, AD_DATASZ_EA);
542     if (header_len < 1) {
543         LOG(log_debug, logtype_default, "ad_header_read_ea: %s", strerror(errno));
544         return -1;
545     }
546
547     if (header_len < AD_HEADER_LEN) {
548         LOG(log_error, logtype_default, "ad_header_read_ea: bogus AppleDouble header.");
549         errno = EIO;
550         return -1;
551     }
552
553     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
554     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
555
556     ad->ad_magic = ntohl( ad->ad_magic );
557     ad->ad_version = ntohl( ad->ad_version );
558
559     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
560         LOG(log_error, logtype_default, "ad_header_read_ea: wrong magic or version");
561         errno = EIO;
562         return -1;
563     }
564
565     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
566     nentries = ntohs( nentries );
567
568     /* Protect against bogus nentries */
569     len = nentries * AD_ENTRY_LEN;
570     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
571         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
572     if (len > header_len - AD_HEADER_LEN) {
573         LOG(log_error, logtype_default, "ad_header_read_ea: can't read entry info.");
574         errno = EIO;
575         return -1;
576     }
577     nentries = len / AD_ENTRY_LEN;
578
579     /* Now parse entries */
580     parse_entries(ad, buf + AD_HEADER_LEN, nentries);
581
582     return 0;
583 }
584
585 /*!
586  * Takes a path to an AppleDouble file and creates the parrent .AppleDouble directory
587  *
588  * Example:
589  * path: "/path/.AppleDouble/file"
590  * => mkdir("/path/.AppleDouble/") (in ad_mkdir())
591  */
592 static int ad_mkrf(const char *path)
593 {
594     char *slash;
595     /*
596      * Probably .AppleDouble doesn't exist, try to mkdir it.
597      */
598     if (NULL == ( slash = strrchr( path, '/' )) ) {
599         return -1;
600     }
601     *slash = '\0';
602     errno = 0;
603     if ( ad_mkdir( path, 0777 ) < 0 ) {
604         return -1;
605     }
606     *slash = '/';
607     return 0;
608 }
609
610 static int ad_mkrf_ea(const char *path _U_)
611 {
612     AFP_PANIC("ad_mkrf_ea: dont use");
613     return 0;
614 }
615
616 static int ad_mkrf_osx(const char *path _U_)
617 {
618     return 0;
619 }
620
621 /* ----------------
622    if we are root change path user/ group
623    It can be a native function for BSD cf. FAQ.Q10
624    path:  pathname to chown
625    stbuf: parent directory inode
626
627    use fstat and fchown or lchown with linux?
628 */
629 #define EMULATE_SUIDDIR
630
631 static int ad_chown(const char *path, struct stat *stbuf)
632 {
633     int ret = 0;
634 #ifdef EMULATE_SUIDDIR
635     uid_t id;
636
637     if (default_uid != (uid_t)-1) {
638         /* we are root (admin) */
639         id = (default_uid)?default_uid:stbuf->st_uid;
640         ret = lchown( path, id, stbuf->st_gid );
641     }
642 #endif
643     return ret;
644 }
645
646 #define DEFMASK 07700   /* be conservative */
647
648 /* ----------------
649    return access right and inode of path parent directory
650 */
651 static int ad_mode_st(const char *path, mode_t *mode, struct stat *stbuf)
652 {
653     if (*mode == 0) {
654         return -1;
655     }
656     if (ad_stat(path, stbuf) != 0) {
657         *mode &= DEFMASK;
658         return -1;
659     }
660     *mode &= stbuf->st_mode;
661     return 0;
662 }
663
664 /* --------------------------- */
665 static int ad_header_upgrade(struct adouble *ad _U_, const char *name _U_)
666 {
667     return 0;
668 }
669
670 static int ad_header_upgrade_ea(struct adouble *ad _U_, const char *name _U_)
671 {
672     AFP_PANIC("ad_header_upgrade_ea: dont use");
673     return 0;
674 }
675
676 /*!
677  * Error handling for adouble header(=metadata) file open error
678  *
679  * We're called because opening ADFLAGS_HF caused an error.
680  * 1. In case ad_open is called with ADFLAGS_NOHF the error is suppressed.
681  * 2. If ad_open was called with ADFLAGS_DF we may have opened the datafork and thus
682  *    ought to close it before returning with an error condition.
683  */
684 static int ad_error(struct adouble *ad, int adflags)
685 {
686     int err = errno;
687     if (adflags & ADFLAGS_NOHF) { /* 1 */
688         return 0;
689     }
690     if (adflags & ADFLAGS_DF) { /* 2 */
691         ad_close( ad, ADFLAGS_DF );
692         err = errno;
693     }
694     return -1 ;
695 }
696
697 /* Map ADFLAGS to open() flags */
698 static int ad2openflags(int adflags)
699 {
700     int oflags = 0;
701
702     if (adflags & ADFLAGS_RDWR)
703         oflags |= O_RDWR;
704     if (adflags & ADFLAGS_RDONLY) {
705         if (adflags & ADFLAGS_SETSHRMD)
706             oflags |= O_RDWR;
707         else
708             oflags |= O_RDONLY;
709     }
710     if (adflags & ADFLAGS_CREATE)
711         oflags |= O_CREAT;
712     if (adflags & ADFLAGS_EXCL)
713         oflags |= O_EXCL;
714     if (adflags & ADFLAGS_TRUNC)
715         oflags |= O_TRUNC;
716
717     return oflags;
718 }
719
720 static int ad_open_df(const char *path, int adflags, mode_t mode, struct adouble *ad)
721 {
722     struct stat st_dir;
723     int         oflags;
724     mode_t      admode;
725     int         st_invalid = -1;
726     ssize_t     lsz;
727
728     LOG(log_debug, logtype_default, "ad_open_df(\"%s\", %04o)",
729         fullpathname(path), mode);
730
731     if (ad_data_fileno(ad) != -1) {
732         /* the file is already open, but we want write access: */
733         if ((adflags & ADFLAGS_RDWR)
734             /* and it was denied the first time: */
735             && (ad->ad_data_fork.adf_flags & O_RDONLY)) {
736                 errno = EACCES;
737                 return -1;
738             }
739         /* it's not new anymore */
740         ad->ad_data_fork.adf_flags &= ~( O_TRUNC | O_CREAT );
741         ad->ad_data_fork.adf_refcount++;
742         return 0;
743     }
744
745     oflags = O_NOFOLLOW | ad2openflags(adflags);
746
747     admode = mode;
748     if ((adflags & ADFLAGS_CREATE)) {
749         st_invalid = ad_mode_st(path, &admode, &st_dir);
750         if ((ad->ad_options & ADVOL_UNIXPRIV))
751             admode = mode;
752     }
753
754     ad->ad_data_fork.adf_fd = open(path, oflags, admode);
755
756     if (ad->ad_data_fork.adf_fd == -1) {
757         switch (errno) {
758         case EACCES:
759         case EPERM:
760         case EROFS:
761             if ((adflags & ADFLAGS_SETSHRMD) && (adflags & ADFLAGS_RDONLY)) {
762                 oflags &= ~O_RDWR;
763                 oflags |= O_RDONLY;
764                 if ((ad->ad_data_fork.adf_fd = open(path, oflags, admode)) == -1)
765                     return -1;
766                 break;
767             }
768             return -1;
769         case OPEN_NOFOLLOW_ERRNO:
770             ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
771             if ((lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN)) <= 0) {
772                 free(ad->ad_data_fork.adf_syml);
773                 return -1;
774             }
775             ad->ad_data_fork.adf_syml[lsz] = 0;
776             ad->ad_data_fork.adf_fd = -2; /* -2 means its a symlink */
777             break;
778         default:
779             return -1;
780         }
781     }
782
783     if (!st_invalid)
784         ad_chown(path, &st_dir); /* just created, set owner if admin (root) */
785
786     ad->ad_data_fork.adf_flags = oflags;
787     adf_lock_init(&ad->ad_data_fork);
788     ad->ad_data_fork.adf_refcount++;
789
790     return 0;
791 }
792
793 /* TODO: error handling */
794 static int ad_open_hf_v2(const char *path, int adflags, mode_t mode, struct adouble *ad)
795 {
796     struct stat st_dir;
797     struct stat st_meta;
798     struct stat *pst = NULL;
799     const char  *ad_p;
800     int         oflags, nocreatflags;
801     mode_t      admode;
802     int         st_invalid = -1;
803
804     if (ad_meta_fileno(ad) != -1) {
805         /* the file is already open, but we want write access: */
806         if ((adflags & ADFLAGS_RDWR) &&
807             /* and it was already denied: */
808             (ad->ad_mdp->adf_flags & O_RDONLY)) {
809             errno = EACCES;
810             return -1;
811         }
812         ad_refresh(path, ad);
813         /* it's not new anymore */
814         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
815         ad->ad_mdp->adf_refcount++;
816         return 0;
817     }
818
819     ad_p = ad->ad_ops->ad_path(path, adflags);
820     oflags = O_NOFOLLOW | ad2openflags(adflags);
821     nocreatflags = oflags & ~(O_CREAT | O_EXCL);
822
823     ad->ad_mdp->adf_fd = open(ad_p, nocreatflags);
824
825     if (ad->ad_mdp->adf_fd != -1) {
826         ad->ad_mdp->adf_flags = nocreatflags;
827     } else {
828         switch (errno) {
829         case EACCES:
830         case EPERM:
831         case EROFS:
832             if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_SETSHRMD)) {
833                 nocreatflags &= ~O_RDWR;
834                 nocreatflags |= O_RDONLY;
835                 if ((ad->ad_mdp->adf_fd = open(ad_p, nocreatflags)) == -1)
836                     return -1;
837                 ad->ad_mdp->adf_flags = nocreatflags;
838                 break;
839             }
840             return -1;
841         case ENOENT:
842             if (!(oflags & O_CREAT))
843                 return ad_error(ad, adflags);
844             /*
845              * We're expecting to create a new adouble header file here
846              */
847             LOG(log_debug, logtype_default, "ad_open(\"%s\"): creating adouble file",
848                 fullpathname(path));
849             admode = mode;
850             errno = 0;
851             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
852             if ((ad->ad_options & ADVOL_UNIXPRIV))
853                 admode = mode;
854             admode = ad_hf_mode(admode);
855             if ((errno == ENOENT) && (ad->ad_vers != AD_VERSION2_OSX)) {
856                 if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
857                     return ad_error(ad, adflags);
858                 }
859                 admode = mode;
860                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
861                 if ((ad->ad_options & ADVOL_UNIXPRIV))
862                     admode = mode;
863                 admode = ad_hf_mode(admode);
864             }
865
866             /* retry with O_CREAT */
867             ad->ad_mdp->adf_fd = open(ad_p, oflags, admode);
868             if ( ad->ad_mdp->adf_fd < 0 )
869                 return ad_error(ad, adflags);
870
871             ad->ad_mdp->adf_flags = oflags;
872             /* just created, set owner if admin owner (root) */
873             if (!st_invalid)
874                 ad_chown(ad_p, &st_dir);
875             break;
876         default:
877             return -1;
878         }
879     }
880
881     if (!(ad->ad_mdp->adf_flags & O_CREAT)) {
882         /* check for 0 length files, treat them as new. */
883         if (fstat(ad->ad_mdp->adf_fd, &st_meta) == 0) {
884             if (st_meta.st_size == 0)
885                 ad->ad_mdp->adf_flags |= O_TRUNC;
886             else
887                 /* we have valid data in st_meta stat structure, reused it in ad_header_read */
888                 pst = &st_meta;
889         }
890     }
891
892     adf_lock_init(ad->ad_mdp);
893     ad->ad_mdp->adf_refcount = 1;
894
895     if ((ad->ad_mdp->adf_flags & ( O_TRUNC | O_CREAT ))) {
896         /* This is a new adouble header file, create it */
897         if (new_ad_header(ad, path, pst, adflags) < 0) {
898             int err = errno;
899             /* the file is already deleted, perm, whatever, so return an error */
900             ad_close(ad, adflags);
901             errno = err;
902             return -1;
903         }
904         ad_flush(ad);
905     } else {
906         /* Read the adouble header in and parse it.*/
907         if (ad->ad_ops->ad_header_read(path, ad, pst) < 0
908             || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0) {
909             int err = errno;
910             ad_close(ad, adflags);
911             errno = err;
912             return -1;
913         }
914     }
915
916     return 0;
917 }
918
919 /* TODO: error handling */
920 static int ad_open_hf_ea(const char *path, int adflags, int mode, struct adouble *ad)
921 {
922     ssize_t rforklen;
923     int oflags;
924     int opened = 0;
925
926     LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\", %s, %04o)",
927         path, adflags2logstr(adflags), mode);
928
929     oflags = O_NOFOLLOW | (ad2openflags(adflags) & ~(O_CREAT | O_TRUNC));
930
931     if (ad_meta_fileno(ad) != -1) {
932         /* the file is already open, but we want write access: */
933         if ((oflags & O_RDWR) &&
934             /* and it was already denied: */
935             (ad->ad_mdp->adf_flags & O_RDONLY)) {
936             LOG(log_error, logtype_default, "ad_open_hf_ea(%s): rw request for ro file: %s",
937                 fullpathname(path), strerror(errno));
938             errno = EACCES;
939             return -1;
940         }
941         /* it's not new anymore */
942         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
943     } else {
944         if (adflags & ADFLAGS_RDWR) {
945             /* Fo a RDONLY adouble we just use sys_lgetxattr instead if sys_fgetxattr */
946             if (adflags & ADFLAGS_DIR)
947                 /* For directories we open the directory RDONYL so we can later fchdir()  */
948                 oflags = (oflags & ~O_RDWR) | O_RDONLY;
949             LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): opening base file for meta adouble EA", path);
950             if ((ad_meta_fileno(ad) = open(path, oflags)) == -1)
951                 goto error;
952             opened = 1;
953             ad->ad_mdp->adf_flags = oflags;
954         }
955     }
956
957     /* Read the adouble header in and parse it.*/
958     if (ad->ad_ops->ad_header_read(path, ad, NULL) != 0) {
959         LOG(log_error, logtype_default, "ad_open_hf_ea: no EA adouble");
960
961         if (!(adflags & ADFLAGS_CREATE)) {
962             errno = ENOENT;
963             goto error;
964         }
965
966         LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): creating metadata EA", path);
967
968         /* It doesnt exist, EPERM or another error */
969         if (!(errno == ENOATTR || errno == ENOENT)) {
970             LOG(log_error, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
971             goto error;
972         }
973
974         /* Create one */
975         if (new_ad_header(ad, path, NULL, adflags) < 0) {
976             LOG(log_error, logtype_default, "ad_open_hf_ea: can't create new header: %s",
977                 fullpathname(path));
978             goto error;
979         }
980         ad->ad_mdp->adf_flags |= O_CREAT; /* mark as just created */
981         ad_flush(ad);
982         LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): created metadata EA", path);
983     }
984
985     ad->ad_mdp->adf_refcount++;
986     (void)ad_reso_size(path, adflags, ad);
987
988     return 0;
989
990 error:
991     if (opened && ad_meta_fileno(ad) != -1) {
992         close(ad_meta_fileno(ad));
993         ad_meta_fileno(ad) = -1;
994         ad->ad_mdp->adf_refcount = 0;
995     }
996     (void)ad_reso_size(path, adflags, ad);
997     return -1;
998 }
999
1000 static int ad_open_hf(const char *path, int adflags, int mode, struct adouble *ad)
1001 {
1002     int ret = 0;
1003
1004     LOG(log_debug, logtype_default, "ad_open_hf(\"%s\", %04o)", path, mode);
1005
1006     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
1007     ad->ad_rlen = 0;
1008
1009     switch (ad->ad_vers) {
1010     case AD_VERSION2:
1011         ret = ad_open_hf_v2(path, adflags, mode, ad);
1012         break;
1013     case AD_VERSION_EA:
1014         ret = ad_open_hf_ea(path, adflags, mode, ad);
1015         break;
1016     default:
1017         ret = -1;
1018         break;
1019     }
1020
1021     if (ret != 0) {
1022         return ad_error(ad, adflags);
1023     }
1024     return ret;
1025 }
1026
1027 /*!
1028  * Get resofork length for adouble:ea
1029  */
1030 static int ad_reso_size(const char *path, int adflags, struct adouble *ad)
1031 {
1032     EC_INIT;
1033     struct stat st;
1034
1035     LOG(log_debug, logtype_default, "ad_reso_size(\"%s\")", path);
1036
1037 #ifdef HAVE_EAFD
1038     int opened = 0;
1039     int eafd = ad_reso_fileno(ad);
1040     if (eafd == -1) {
1041         EC_NEG1( eafd = sys_getxattrfd(path, O_RDONLY) );
1042         opened = 1;
1043     }
1044     EC_NEG1( rlen = fstat(eafd, &st) );
1045     ad->ad_rlen = st.st_size;
1046 #else
1047     const char *rfpath;
1048     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags));
1049     EC_ZERO( lstat(rfpath, &st));
1050     if (st.st_size > ADEDOFF_RFORK_OSX)
1051         ad->ad_rlen = st.st_size - ADEDOFF_RFORK_OSX;
1052     else
1053         ad->ad_rlen = 0;
1054 #endif
1055
1056     LOG(log_debug, logtype_default, "ad_reso_size(\"%s\"): size: %zd", path, ad->ad_rlen);
1057
1058 EC_CLEANUP:
1059 #ifdef HAVE_EAFD
1060     if (opened)
1061         close(eafd);
1062 #endif
1063     if (ret != 0)
1064         ad->ad_rlen = 0;
1065     EC_EXIT;
1066 }
1067
1068 /*!
1069  * Open ressource fork
1070  *
1071  * Only for adouble:ea, a nullop otherwise because adouble:v2 has the ressource fork as part
1072  * of the adouble file which is openend by ADFLAGS_HF.
1073  */
1074 static int ad_open_rf(const char *path, int adflags, int mode, struct adouble *ad)
1075 {
1076     EC_INIT;
1077     int oflags;
1078     int closeflags = adflags & (ADFLAGS_DF | ADFLAGS_HF);
1079     ssize_t rlen;
1080 #ifndef HAVE_EAFD
1081     const char *rfpath;
1082     struct stat st;
1083 #endif
1084
1085     if (ad->ad_vers != AD_VERSION_EA)
1086         return 0;
1087
1088     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\", %04o)", path, mode);
1089
1090     oflags = O_NOFOLLOW | (ad2openflags(adflags) & ~O_CREAT);
1091
1092     if (ad_reso_fileno(ad) != -1) {
1093         /* the file is already open, but we want write access: */
1094         if ((adflags & ADFLAGS_RDWR)
1095             /* and it was already denied: */
1096             && (ad->ad_rfp->adf_flags & O_RDONLY)) {
1097             errno = EACCES;
1098             return -1;
1099         }
1100         ad->ad_rfp->adf_flags &= ~( O_TRUNC | O_CREAT );
1101         ad->ad_rfp->adf_refcount++;
1102         EC_NEG1_LOG( ad_reso_size(path, adflags, ad));
1103         return 0;
1104     }
1105 #ifdef HAVE_EAFD
1106     if ((ad_reso_fileno(ad) = sys_getxattrfd(path, oflags)) == -1) {
1107         if (!(adflags & ADFLAGS_CREATE))
1108             EC_FAIL;
1109         oflags |= O_CREAT;
1110         EC_NEG1_LOG( ad_reso_fileno(ad) = sys_getxattrfd(path, oflags, 0666) ); 
1111     }
1112 #else
1113     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags) );
1114     if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1115         if (!(adflags & ADFLAGS_CREATE))
1116             EC_FAIL;
1117         oflags |= O_CREAT;
1118         EC_NEG1_LOG( ad_reso_fileno(ad) = open(rfpath, oflags, mode) );
1119         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork: \"%s\"",
1120             path, rfpath);
1121     }
1122 #endif
1123
1124     ad->ad_rfp->adf_refcount = 1;
1125     ad->ad_rfp->adf_flags = oflags;
1126
1127 #ifndef HAVE_EAFD
1128     EC_ZERO_LOG( fstat(ad_reso_fileno(ad), &st) );
1129     if (ad->ad_rfp->adf_flags & O_CREAT) {
1130         /* This is a new adouble header file, create it */
1131         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, initializing: \"%s\"",
1132             path, rfpath);
1133         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, flushing: \"%s\"",
1134             path, rfpath);
1135         ad_flush(ad);
1136     } else {
1137         /* Read the adouble header */
1138         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): reading adouble rfork: \"%s\"",
1139             path, rfpath);
1140         EC_NEG1_LOG( ad_header_read_osx(NULL, ad, &st) );
1141     }
1142 #endif
1143
1144     (void)ad_reso_size(path, adflags, ad);
1145
1146 EC_CLEANUP:
1147     if (ret != 0) {
1148         if (ad_reso_fileno(ad) != -1) {
1149             close(ad_reso_fileno(ad));
1150             ad_reso_fileno(ad) = -1;
1151             ad->ad_rfp->adf_refcount = 0;
1152         }
1153         if (adflags & ADFLAGS_NORF) {
1154             ret = 0;
1155         } else {
1156             int err = errno;
1157             (void)ad_close(ad, closeflags);
1158             errno = err;
1159         }
1160         ad->ad_rlen = 0;
1161     }
1162
1163     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): END", path);
1164
1165     EC_EXIT;
1166 }
1167
1168 /***********************************************************************************
1169  * API functions
1170  ********************************************************************************* */
1171
1172 const char *ad_path_ea( const char *path, int adflags _U_)
1173 {
1174     return path;
1175 }
1176
1177 const char *ad_path_osx(const char *path, int adflags _U_)
1178 {
1179     static char pathbuf[ MAXPATHLEN + 1];
1180     char    c, *slash, buf[MAXPATHLEN + 1];
1181
1182     if (!strcmp(path,".")) {
1183         /* fixme */
1184         getcwd(buf, MAXPATHLEN);
1185     }
1186     else {
1187         strlcpy(buf, path, MAXPATHLEN +1);
1188     }
1189     if (NULL != ( slash = strrchr( buf, '/' )) ) {
1190         c = *++slash;
1191         *slash = '\0';
1192         strlcpy( pathbuf, buf, MAXPATHLEN +1);
1193         *slash = c;
1194     } else {
1195         pathbuf[ 0 ] = '\0';
1196         slash = buf;
1197     }
1198     strlcat( pathbuf, "._", MAXPATHLEN  +1);
1199     strlcat( pathbuf, slash, MAXPATHLEN +1);
1200     return pathbuf;
1201 }
1202
1203 /*
1204  * Put the .AppleDouble where it needs to be:
1205  *
1206  *      /   a/.AppleDouble/b
1207  *  a/b
1208  *      \   b/.AppleDouble/.Parent
1209  *
1210  * FIXME: should do something for pathname > MAXPATHLEN
1211  */
1212 const char *ad_path( const char *path, int adflags)
1213 {
1214     static char pathbuf[ MAXPATHLEN + 1];
1215     const char *slash;
1216     size_t  l ;
1217
1218     if ( adflags & ADFLAGS_DIR ) {
1219         l = strlcpy( pathbuf, path, sizeof(pathbuf));
1220
1221         if ( l && l < MAXPATHLEN) {
1222             pathbuf[l++] = '/';
1223         }
1224         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
1225     } else {
1226         if (NULL != ( slash = strrchr( path, '/' )) ) {
1227             slash++;
1228             l = slash - path;
1229             /* XXX we must return NULL here and test in the caller */
1230             if (l > MAXPATHLEN)
1231                 l = MAXPATHLEN;
1232             memcpy( pathbuf, path, l);
1233         } else {
1234             l = 0;
1235             slash = path;
1236         }
1237         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
1238         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
1239     }
1240
1241     return( pathbuf );
1242 }
1243
1244 /* -------------------------
1245  * Support inherited protection modes for AppleDouble files.  The supplied
1246  * mode is ANDed with the parent directory's mask value in lieu of "umask",
1247  * and that value is returned.
1248  */
1249 char *ad_dir(const char *path)
1250 {
1251     static char     modebuf[ MAXPATHLEN + 1];
1252     char        *slash;
1253     /*
1254      * For a path with directories in it, remove the final component
1255      * (path or subdirectory name) to get the name we want to stat.
1256      * For a path which is just a filename, use "." instead.
1257      */
1258     slash = strrchr( path, '/' );
1259     if (slash) {
1260         size_t len;
1261
1262         len = slash - path;
1263         if (len >= MAXPATHLEN) {
1264             errno = ENAMETOOLONG;
1265             return NULL;  /* can't do it */
1266         }
1267         memcpy( modebuf, path, len );
1268         modebuf[len] = '\0';
1269         /* is last char a '/' ? */
1270         if (slash[1] == 0) {
1271             slash = modebuf+ len;
1272             /* remove them */
1273             while (modebuf < slash && slash[-1] == '/') {
1274                 --slash;
1275             }
1276             if (modebuf == slash) {
1277                 goto use_cur;
1278             }
1279             *slash = '\0';
1280             while (modebuf < slash && *slash != '/') {
1281                 --slash;
1282             }
1283             if (modebuf == slash) {
1284                 goto use_cur;
1285             }
1286             *slash = '\0';      /* remove pathname component */
1287         }
1288         return modebuf;
1289     }
1290 use_cur:
1291     modebuf[0] = '.';   /* use current directory */
1292     modebuf[1] = '\0';
1293     return modebuf;
1294 }
1295
1296 int ad_setfuid(const uid_t id)
1297 {
1298     default_uid = id;
1299     return 0;
1300 }
1301
1302 /* ---------------- */
1303 uid_t ad_getfuid(void)
1304 {
1305     return default_uid;
1306 }
1307
1308 /* ----------------
1309    stat path parent directory
1310 */
1311 int ad_stat(const char *path, struct stat *stbuf)
1312 {
1313     char *p;
1314
1315     p = ad_dir(path);
1316     if (!p)
1317         return -1;
1318     return lstat( p, stbuf );
1319 }
1320
1321 /* ----------------
1322    return access right of path parent directory
1323 */
1324 int ad_mode( const char *path, mode_t mode)
1325 {
1326     struct stat     stbuf;
1327     ad_mode_st(path, &mode, &stbuf);
1328     return mode;
1329 }
1330
1331 /*
1332  * Use mkdir() with mode bits taken from ad_mode().
1333  */
1334 int ad_mkdir( const char *path, mode_t mode)
1335 {
1336     int ret;
1337     int st_invalid;
1338     struct stat stbuf;
1339
1340     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
1341         path, mode, getcwdpath());
1342
1343     st_invalid = ad_mode_st(path, &mode, &stbuf);
1344     ret = mkdir( path, mode );
1345     if (ret || st_invalid)
1346         return ret;
1347     ad_chown(path, &stbuf);
1348
1349     return ret;
1350 }
1351
1352 static void ad_init_func(struct adouble *ad)
1353 {
1354     switch (ad->ad_vers) {
1355     case AD_VERSION2:
1356         ad->ad_ops = &ad_adouble;
1357         ad->ad_rfp = &ad->ad_resource_fork;
1358         ad->ad_mdp = &ad->ad_resource_fork;
1359         break;
1360     case AD_VERSION_EA:
1361         ad->ad_ops = &ad_adouble_ea;
1362         ad->ad_rfp = &ad->ad_resource_fork;
1363         ad->ad_mdp = &ad->ad_data_fork;
1364         break;
1365     default:
1366         AFP_PANIC("ad_init: unknown AD version");
1367     }
1368
1369
1370     ad_data_fileno(ad) = -1;
1371     ad_reso_fileno(ad) = -1;
1372     ad_meta_fileno(ad) = -1;
1373     ad->ad_refcount = 1;
1374     return;
1375 }
1376
1377 void ad_init_old(struct adouble *ad, int flags, int options)
1378 {
1379     memset(ad, 0, sizeof(struct adouble));
1380     ad->ad_vers = flags;
1381     ad->ad_options = options;
1382     ad_init_func(ad);
1383 }
1384
1385 void ad_init(struct adouble *ad, const struct vol * restrict vol)
1386 {
1387     memset(ad, 0, sizeof(struct adouble));
1388     ad->ad_vers = vol->v_adouble;
1389     ad->ad_options = vol->v_ad_options;
1390     ad_init_func(ad);
1391 }
1392
1393 /*!
1394  * Open data-, metadata(header)- or ressource fork
1395  *
1396  * ad_open(struct adouble *ad, const char *path, int adflags, int flags)
1397  * ad_open(struct adouble *ad, const char *path, int adflags, int flags, mode_t mode)
1398  *
1399  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1400  * @code
1401  *      struct adoube ad;
1402  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1403  * @endcode
1404  *
1405  * Open a files data fork, metadata fork or ressource fork.
1406  *
1407  * @param ad        (rw) pointer to struct adouble
1408  * @param path      (r)  Path to file or directory
1409  * @param adflags   (r)  Flags specifying which fork to open, can be or'd:
1410  *                         ADFLAGS_DF:        open data fork
1411  *                         ADFLAGS_RF:        open ressource fork
1412  *                         ADFLAGS_HF:        open header (metadata) file
1413  *                         ADFLAGS_NOHF:      it's not an error if header file couldn't be opened
1414  *                         ADFLAGS_NORF:      it's not an error if reso fork couldn't be opened
1415  *                         ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags
1416  *
1417  *                       Access mode for the forks:
1418  *                         ADFLAGS_RDONLY:    open read only
1419  *                         ADFLAGS_RDWR:      open read write
1420  *
1421  *                       Creation flags:
1422  *                         ADFLAGS_CREATE:    create if not existing
1423  *                         ADFLAGS_TRUNC:     truncate
1424  *
1425  *                       Special flags:
1426  *                         ADFLAGS_CHECK_OF:  check for open forks from us and other afpd's
1427  *                         ADFLAGS_SETSHRMD:  this adouble struct will be used to set sharemode locks.
1428  *                                            This basically results in the files being opened RW instead of RDONLY.
1429  * @param mode      (r)  mode used with O_CREATE
1430  *
1431  * The open mode flags (rw vs ro) have to take into account all the following requirements:
1432  * - we remember open fds for files because me must avoid a single close releasing fcntl locks for other
1433  *   fds of the same file
1434  *
1435  * @returns 0 on success, any other value indicates an error
1436  */
1437 int ad_open(struct adouble *ad, const char *path, int adflags, ...)
1438 {
1439     EC_INIT;
1440     va_list args;
1441     mode_t mode = 0;
1442
1443     LOG(log_debug, logtype_default, "ad_open(\"%s\", %s)",
1444         fullpathname(path), adflags2logstr(adflags));
1445
1446     LOG(log_debug, logtype_default,
1447         "ad_open(\"%s\", %s) [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1448         fullpathname(path), adflags2logstr(adflags),
1449         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1450         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1451         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1452
1453     if (adflags & ADFLAGS_CHECK_OF)
1454         /* Checking for open forks requires sharemode lock support (ie RDWR instead of RDONLY) */
1455         adflags |= ADFLAGS_SETSHRMD;
1456
1457     if ((ad->ad_vers == AD_VERSION2) && (adflags & ADFLAGS_RF)) {
1458         adflags |= ADFLAGS_HF;
1459         if (adflags & ADFLAGS_NORF)
1460             adflags |= ADFLAGS_NOHF;
1461     }
1462
1463     if (ad->ad_inited != AD_INITED) {
1464         ad->ad_adflags = adflags;
1465         ad->ad_inited = AD_INITED;
1466     } else {
1467         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1468         if (ad->ad_resource_fork.adf_refcount > 0)
1469             ad->ad_open_forks |= ATTRBIT_ROPEN;
1470     }
1471
1472     va_start(args, adflags);
1473     if (adflags & ADFLAGS_CREATE)
1474         mode = va_arg(args, mode_t);
1475     va_end(args);
1476
1477     if (adflags & ADFLAGS_DF) {
1478         EC_ZERO( ad_open_df(path, adflags, mode, ad) );
1479     }
1480
1481     if (adflags & ADFLAGS_HF) {
1482         EC_ZERO( ad_open_hf(path, adflags, mode, ad) );
1483     }
1484
1485     if (adflags & ADFLAGS_RF) {
1486         EC_ZERO( ad_open_rf(path, adflags, mode, ad) );
1487     }
1488
1489     if (adflags & ADFLAGS_CHECK_OF) {
1490         ad->ad_open_forks |= ad_openforks(ad, ad->ad_open_forks);
1491     }
1492
1493 EC_CLEANUP:
1494     LOG(log_debug, logtype_default,
1495         "ad_open(\"%s\"): result: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1496         fullpathname(path), ret,
1497         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1498         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1499         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1500
1501     EC_EXIT;
1502 }
1503
1504 /*!
1505  * @brief open metadata, possibly as root
1506  *
1507  * Return only metadata but try very hard ie at first try as user, then try as root.
1508  *
1509  * @param name  name of file/dir
1510  * @param flags ADFLAGS_DIR: name is a directory \n
1511  *              ADFLAGS_CHECK_OF: test if name is open by us or another afpd process
1512  *
1513  * @param adp   pointer to struct adouble
1514  */
1515 int ad_metadata(const char *name, int flags, struct adouble *adp)
1516 {
1517     uid_t uid;
1518     int   ret, err, oflags;
1519
1520     /* Sanitize flags */
1521     oflags = (flags & (ADFLAGS_CHECK_OF | ADFLAGS_DIR)) | ADFLAGS_HF | ADFLAGS_RDONLY;    
1522
1523     if ((ret = ad_open(adp, name, oflags)) < 0 && errno == EACCES) {
1524         uid = geteuid();
1525         if (seteuid(0)) {
1526             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1527             errno = EACCES;
1528             return -1;
1529         }
1530         /* we are root open read only */
1531         ret = ad_open(adp, name, oflags);
1532         err = errno;
1533         if ( seteuid(uid) < 0) {
1534             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1535             exit(EXITERR_SYS);
1536         }
1537         errno = err;
1538     }
1539
1540     return ret;
1541 }
1542
1543 /*
1544  * @brief openat like wrapper for ad_metadata
1545  */
1546 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1547 {
1548     int ret = 0;
1549     int cwdfd = -1;
1550
1551     if (dirfd != -1) {
1552         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1553             ret = -1;
1554             goto exit;
1555         }
1556     }
1557
1558     if (ad_metadata(name, flags, adp) < 0) {
1559         ret = -1;
1560         goto exit;
1561     }
1562
1563     if (dirfd != -1) {
1564
1565         if (fchdir(cwdfd) != 0) {
1566             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1567             exit(EXITERR_SYS);
1568         }
1569     }
1570
1571 exit:
1572     if (cwdfd != -1)
1573         close(cwdfd);
1574
1575     return ret;
1576
1577 }
1578
1579 int ad_refresh(const char *path, struct adouble *ad)
1580 {
1581     switch (ad->ad_vers) {
1582     case AD_VERSION2:
1583         if (ad_meta_fileno(ad) == -1)
1584             return -1;
1585         return ad->ad_ops->ad_header_read(NULL, ad, NULL);
1586         break;
1587     case AD_VERSION_EA:
1588 #ifdef HAVE_EAFD
1589         if (AD_META_OPEN(ad)) {
1590             if (ad_data_fileno(ad) == -1)
1591                 return -1;
1592             // TODO: read meta EA
1593         }
1594
1595         if (AD_RSRC_OPEN(ad)) {
1596             if (ad_reso_fileno(ad) == -1)
1597                 return -1;
1598             ssize_t len;
1599             if ((len = fstat(ad_reso_fileno(ad))) == -1)
1600                 return -1;
1601             ad->ad_rlen = len;
1602         }
1603 #else
1604         if (AD_META_OPEN(ad)) {
1605             if (ad_data_fileno(ad) == -1)
1606                 return -1;
1607             // TODO: read meta EA
1608         }
1609         if (AD_RSRC_OPEN(ad)) {
1610             if (ad_reso_fileno(ad) == -1)
1611                 return -1;
1612             if (ad_header_read_osx(path, ad, NULL) < 0)
1613                 return -1;
1614         }
1615 #endif
1616         return ad->ad_ops->ad_header_read(path, ad, NULL);
1617         break;
1618     default:
1619         return -1;
1620         break;
1621     }
1622
1623 }
1624
1625 int ad_openat(struct adouble  *ad,
1626               int dirfd,  /* dir fd openat like */
1627               const char *path,
1628               int adflags, ...)
1629 {
1630     EC_INIT;
1631     int cwdfd = -1;
1632     va_list args;
1633     mode_t mode;
1634
1635     if (dirfd != -1) {
1636         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0))
1637             EC_FAIL;
1638     }
1639
1640     va_start(args, adflags);
1641     if (adflags & ADFLAGS_CREATE)
1642         mode = va_arg(args, mode_t);
1643     va_end(args);
1644
1645     EC_NEG1( ad_open(ad, path, adflags, mode) );
1646
1647     if (dirfd != -1) {
1648         if (fchdir(cwdfd) != 0) {
1649             AFP_PANIC("ad_openat: cant chdir back");
1650         }
1651     }
1652
1653 EC_CLEANUP:
1654     if (cwdfd != -1)
1655         close(cwdfd);
1656
1657     return ret;
1658 }