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