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