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