]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
2fd01d97891514882a67266a35e7794460cb9094
[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
110
111 static const char *ad_path_osx(const char *path, int adflags);
112 static int ad_mkrf_osx(const char *path);
113
114
115 static struct adouble_fops ad_adouble = {
116     &ad_path,
117     &ad_mkrf,
118     &ad_rebuild_adouble_header,
119     &ad_header_read,
120     &ad_header_upgrade,
121 };
122
123 static struct adouble_fops ad_adouble_ea = {
124 #ifdef HAVE_EAFD
125     &ad_path_ea,
126     &ad_mkrf_ea,
127 #else
128     &ad_path_osx,
129     &ad_mkrf_osx,
130 #endif
131     &ad_rebuild_adouble_header,
132     &ad_header_read_ea,
133     &ad_header_upgrade_ea,
134 };
135
136 static struct adouble_fops ad_osx = {
137     &ad_path_osx,
138     &ad_mkrf_osx,
139     &ad_rebuild_adouble_header,
140     &ad_header_read,
141     &ad_header_upgrade,
142 };
143
144 static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
145     {ADEID_NAME,        ADEDOFF_NAME_V2,     ADEDLEN_INIT},
146     {ADEID_COMMENT,     ADEDOFF_COMMENT_V2,  ADEDLEN_INIT},
147     {ADEID_FILEDATESI,  ADEDOFF_FILEDATESI,  ADEDLEN_FILEDATESI},
148     {ADEID_FINDERI,     ADEDOFF_FINDERI_V2,  ADEDLEN_FINDERI},
149     {ADEID_DID,         ADEDOFF_DID,         ADEDLEN_DID},
150     {ADEID_AFPFILEI,    ADEDOFF_AFPFILEI,    ADEDLEN_AFPFILEI},
151     {ADEID_SHORTNAME,   ADEDOFF_SHORTNAME,   ADEDLEN_INIT},
152     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
153     {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV,     ADEDLEN_INIT},
154     {ADEID_PRIVINO,     ADEDOFF_PRIVINO,     ADEDLEN_INIT},
155     {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN,     ADEDLEN_INIT},
156     {ADEID_PRIVID,      ADEDOFF_PRIVID,      ADEDLEN_INIT},
157     {ADEID_RFORK,       ADEDOFF_RFORK_V2,    ADEDLEN_INIT},
158     {0, 0, 0}
159 };
160
161 /* Using Extended Attributes */
162 static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
163     {ADEID_FINDERI,    ADEDOFF_FINDERI_EA,    ADEDLEN_FINDERI},
164     {ADEID_COMMENT,    ADEDOFF_COMMENT_EA,    ADEDLEN_INIT},
165     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_EA, ADEDLEN_FILEDATESI},
166     {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_EA,   ADEDLEN_AFPFILEI},
167     {ADEID_PRIVID,     ADEDOFF_PRIVID,        ADEDLEN_INIT},
168     {0, 0, 0}
169 };
170
171 /* fallback for EAs */
172 static const struct entry entry_order_osx[ADEID_NUM_OSX +1] = {
173     {ADEID_FINDERI, ADEDOFF_FINDERI_OSX, ADEDLEN_FINDERI},
174     {ADEID_RFORK, ADEDOFF_RFORK_OSX, ADEDLEN_INIT},
175     {0, 0, 0}
176 };
177
178 #define ADFLAGS2LOGSTRBUFSIZ 128
179 const char *adflags2logstr(int adflags)
180 {
181     int first = 1;
182     static char buf[ADFLAGS2LOGSTRBUFSIZ];
183
184     buf[0] = 0;
185
186     if (adflags & ADFLAGS_DF) {
187         strlcat(buf, "DF", ADFLAGS2LOGSTRBUFSIZ);
188         first = 0;
189     }
190     if (adflags & ADFLAGS_RF) {
191         if (!first)
192             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
193         strlcat(buf, "RF", ADFLAGS2LOGSTRBUFSIZ);
194         first = 0;
195     }
196     if (adflags & ADFLAGS_HF) {
197         if (!first)
198             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
199         strlcat(buf, "HF", ADFLAGS2LOGSTRBUFSIZ);
200         first = 0;
201     }
202     if (adflags & ADFLAGS_NOHF) {
203         if (!first)
204             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
205         strlcat(buf, "NOHF", ADFLAGS2LOGSTRBUFSIZ);
206         first = 0;
207     }
208     if (adflags & ADFLAGS_DIR) {
209         if (!first)
210             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
211         strlcat(buf, "DIR", ADFLAGS2LOGSTRBUFSIZ);
212         first = 0;
213     }
214     if (adflags & ADFLAGS_CHECK_OF) {
215         if (!first)
216             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
217         strlcat(buf, "OF", ADFLAGS2LOGSTRBUFSIZ);
218         first = 0;
219     }
220     if (adflags & ADFLAGS_RDWR) {
221         if (!first)
222             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
223         strlcat(buf, "O_RDWR", ADFLAGS2LOGSTRBUFSIZ);
224         first = 0;
225     }
226     if (adflags & ADFLAGS_RDONLY) {
227         if (!first)
228             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
229         strlcat(buf, "O_RDONLY", ADFLAGS2LOGSTRBUFSIZ);
230         first = 0;
231     }
232     if (adflags & ADFLAGS_CREATE) {
233         if (!first)
234             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
235         strlcat(buf, "O_CREAT", ADFLAGS2LOGSTRBUFSIZ);
236         first = 0;
237     }
238     if (adflags & ADFLAGS_EXCL) {
239         if (!first)
240             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
241         strlcat(buf, "O_EXCL", ADFLAGS2LOGSTRBUFSIZ);
242         first = 0;
243     }
244     if (adflags & ADFLAGS_TRUNC) {
245         if (!first)
246             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
247         strlcat(buf, "O_TRUNC", ADFLAGS2LOGSTRBUFSIZ);
248         first = 0;
249     }
250
251     return buf;
252 }
253
254 static uint32_t get_eid(uint32_t eid)
255 {
256     if (eid <= 15)
257         return eid;
258     if (eid == AD_DEV)
259         return ADEID_PRIVDEV;
260     if (eid == AD_INO)
261         return ADEID_PRIVINO;
262     if (eid == AD_SYN)
263         return ADEID_PRIVSYN;
264     if (eid == AD_ID)
265         return ADEID_PRIVID;
266
267     return 0;
268 }
269
270 /* ----------------------------------- */
271 static int new_ad_header(struct adouble *ad, const char *path, struct stat *stp, int adflags)
272 {
273     const struct entry  *eid;
274     uint16_t            ashort;
275     struct stat         st;
276
277     LOG(log_debug, logtype_default, "new_ad_header(\"%s\")", path);
278
279     if (stp == NULL) {
280         stp = &st;
281         if (lstat(path, &st) != 0)
282             return -1;
283     }
284
285     ad->ad_magic = AD_MAGIC;
286     ad->ad_version = ad->ad_vers & 0x0f0000;
287     if (!ad->ad_version) {
288         ad->ad_version = AD_VERSION;
289     }
290
291
292     memset(ad->ad_data, 0, sizeof(ad->ad_data));
293
294     if (ad->ad_vers == AD_VERSION2)
295         eid = entry_order2;
296     else if (ad->ad_vers == AD_VERSION_EA)
297         eid = entry_order_ea;
298     else if (ad->ad_vers == AD_VERSION2_OSX)
299         eid = entry_order_osx;
300     else {
301         return -1;
302     }
303
304     while (eid->id) {
305         ad->ad_eid[eid->id].ade_off = eid->offset;
306         ad->ad_eid[eid->id].ade_len = eid->len;
307         eid++;
308     }
309
310     /* put something sane in the directory finderinfo */
311     if (ad->ad_vers != AD_VERSION2_OSX) {
312         if ((adflags & ADFLAGS_DIR)) {
313             /* set default view */
314             ashort = htons(FINDERINFO_CLOSEDVIEW);
315             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
316         } else {
317             /* set default creator/type fields */
318             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
319             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
320         }
321
322         /* make things invisible */
323         if ((ad->ad_options & ADVOL_INVDOTS) && (*path == '.')) {
324             ashort = htons(ATTRBIT_INVISIBLE);
325             ad_setattr(ad, ashort);
326             ashort = htons(FINDERINFO_INVISIBLE);
327             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
328         }
329
330         /* put something sane in the date fields */
331         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, stp->st_mtime);
332         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, stp->st_mtime);
333         ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, stp->st_mtime);
334         ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
335     }
336     return 0;
337 }
338
339 /* -------------------------------------
340    read in the entries
341 */
342 static void parse_entries(struct adouble *ad, char *buf, uint16_t nentries)
343 {
344     uint32_t   eid, len, off;
345     int        warning = 0;
346
347     /* now, read in the entry bits */
348     for (; nentries > 0; nentries-- ) {
349         memcpy(&eid, buf, sizeof( eid ));
350         eid = get_eid(ntohl(eid));
351         buf += sizeof( eid );
352         memcpy(&off, buf, sizeof( off ));
353         off = ntohl( off );
354         buf += sizeof( off );
355         memcpy(&len, buf, sizeof( len ));
356         len = ntohl( len );
357         buf += sizeof( len );
358
359         if (eid
360             && eid < ADEID_MAX
361             && off < sizeof(ad->ad_data)
362             && (off + len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
363             ad->ad_eid[ eid ].ade_off = off;
364             ad->ad_eid[ eid ].ade_len = len;
365         } else if (!warning) {
366             warning = 1;
367             LOG(log_warning, logtype_default, "parse_entries: bogus eid: %d", eid);
368         }
369     }
370 }
371
372 /* this reads enough of the header so that we can figure out all of
373  * the entry lengths and offsets. once that's done, we just read/mmap
374  * the rest of the header in.
375  *
376  * NOTE: we're assuming that the resource fork is kept at the end of
377  *       the file. also, mmapping won't work for the hfs fs until it
378  *       understands how to mmap header files. */
379 static int ad_header_read(const char *path _U_, struct adouble *ad, struct stat *hst)
380 {
381     char                *buf = ad->ad_data;
382     uint16_t            nentries;
383     int                 len;
384     ssize_t             header_len;
385     struct stat         st;
386
387     /* read the header */
388     if ((header_len = adf_pread( ad->ad_mdp, buf, AD_DATASZ, 0)) < 0) {
389         return -1;
390     }
391     if (header_len < AD_HEADER_LEN) {
392         errno = EIO;
393         return -1;
394     }
395
396     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
397     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
398     ad->ad_magic = ntohl( ad->ad_magic );
399     ad->ad_version = ntohl( ad->ad_version );
400
401     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
402         LOG(log_error, logtype_default, "ad_open: can't parse AppleDouble header.");
403         errno = EIO;
404         return -1;
405     }
406
407     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
408     nentries = ntohs( nentries );
409
410     /* read in all the entry headers. if we have more than the
411      * maximum, just hope that the rfork is specified early on. */
412     len = nentries*AD_ENTRY_LEN;
413
414     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
415         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
416
417     buf += AD_HEADER_LEN;
418     if (len > header_len - AD_HEADER_LEN) {
419         LOG(log_error, logtype_default, "ad_header_read: can't read entry info.");
420         errno = EIO;
421         return -1;
422     }
423
424     /* figure out all of the entry offsets and lengths. if we aren't
425      * able to read a resource fork entry, bail. */
426     nentries = len / AD_ENTRY_LEN;
427     parse_entries(ad, buf, nentries);
428     if (!ad_getentryoff(ad, ADEID_RFORK)
429         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
430         ) {
431         LOG(log_error, logtype_default, "ad_header_read: problem with rfork entry offset.");
432         errno = EIO;
433         return -1;
434     }
435
436     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
437         LOG(log_error, logtype_default, "ad_header_read: can't read in entries.");
438         errno = EIO;
439         return -1;
440     }
441
442     if (hst == NULL) {
443         hst = &st;
444         if (fstat(ad->ad_mdp->adf_fd, &st) < 0) {
445             return 1; /* fail silently */
446         }
447     }
448
449     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
450
451     return 0;
452 }
453
454 /* Read an ._ file, only uses the resofork, finderinfo is taken from EA */
455 static int ad_header_read_osx(const char *path _U_, struct adouble *ad, struct stat *hst)
456 {
457     EC_INIT;
458     struct adouble      adosx;
459     char                *buf = &adosx.ad_data[0];
460     uint16_t            nentries;
461     int                 len;
462     ssize_t             header_len;
463     struct stat         st;
464
465     memset(buf, 0, sizeof(adosx.ad_data));
466
467     /* read the header */
468     EC_NEG1( header_len = adf_pread(ad->ad_rfp, buf, AD_DATASZ_OSX, 0) );
469
470     if (header_len < AD_HEADER_LEN) {
471         errno = EIO;
472         return -1;
473     }
474
475     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
476     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
477     adosx.ad_magic = ntohl(adosx.ad_magic);
478     adosx.ad_version = ntohl(adosx.ad_version);
479
480     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
481         LOG(log_error, logtype_afpd, "ad_header_read_osx: can't parse AppleDouble header");
482         errno = EIO;
483         return -1;
484     }
485
486     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
487     nentries = ntohs(nentries);
488     len = nentries * AD_ENTRY_LEN;
489
490     if (len + AD_HEADER_LEN > sizeof(adosx.ad_data))
491         len = sizeof(adosx.ad_data) - AD_HEADER_LEN;
492
493     buf += AD_HEADER_LEN;
494     if (len > header_len - AD_HEADER_LEN) {
495         LOG(log_error, logtype_afpd, "ad_header_read_osx: can't read entry info.");
496         errno = EIO;
497         return -1;
498     }
499
500     nentries = len / AD_ENTRY_LEN;
501     parse_entries(&adosx, buf, nentries);
502
503     if (ad_getentryoff(&adosx, ADEID_RFORK) == 0
504         || ad_getentryoff(&adosx, ADEID_RFORK) > sizeof(ad->ad_data)
505         || ad_getentryoff(&adosx, ADEID_RFORK) > header_len
506         ) {
507         LOG(log_error, logtype_afpd, "ad_header_read_osx: problem with rfork entry offset.");
508         errno = EIO;
509         return -1;
510     }
511
512     if (hst == NULL) {
513         hst = &st;
514         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
515     }
516
517     ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(&adosx, ADEID_RFORK));
518     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
519
520 EC_CLEANUP:
521     EC_EXIT;
522 }
523
524 static int ad_header_read_ea(const char *path, struct adouble *ad, struct stat *hst _U_)
525 {
526     uint16_t nentries;
527     int      len;
528     ssize_t  header_len;
529     char     *buf = ad->ad_data;
530
531     /* read the header */
532     if (ad_meta_fileno(ad) == -1 && 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\", %04o)", path, mode);
926
927     oflags = O_NOFOLLOW | (ad2openflags(adflags) & ~(O_CREAT | O_TRUNC));
928
929     if (ad_meta_fileno(ad) != -1) {
930         /* the file is already open, but we want write access: */
931         if ((adflags & ADFLAGS_RDWR) &&
932             /* and it was already denied: */
933             (ad->ad_mdp->adf_flags & O_RDONLY)) {
934             LOG(log_error, logtype_default, "ad_open_hf_ea(%s): rw request for ro file: %s",
935                 fullpathname(path), strerror(errno));
936             errno = EACCES;
937             return -1;
938         }
939         /* it's not new anymore */
940         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
941         ad->ad_mdp->adf_refcount++;
942     } else {
943         if (adflags & ADFLAGS_RDWR) {
944             /* Fo a RDONLY adouble we just use sys_lgetxattr instead if sys_fgetxattr */
945             LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): opening for base file for meta adouble EA", path);
946             if ((ad_meta_fileno(ad) = open(path, oflags)) == -1)
947                 goto error;
948             ad->ad_mdp->adf_flags = oflags;
949         }
950         ad->ad_mdp->adf_refcount = 1;
951     }
952
953     /* Read the adouble header in and parse it.*/
954     if (ad->ad_ops->ad_header_read(path, ad, NULL) != 0) {
955         LOG(log_error, logtype_default, "ad_open_hf_ea: no EA adouble");
956
957         if (!(adflags & ADFLAGS_CREATE))
958             goto error;
959
960         LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): creating metadata EA", path);
961
962         /* It doesnt exist, EPERM or another error */
963         if (!(errno == ENOATTR || errno == ENOENT)) {
964             LOG(log_error, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
965             goto error;
966         }
967
968         /* Create one */
969         if (new_ad_header(ad, path, NULL, adflags) < 0) {
970             LOG(log_error, logtype_default, "ad_open_hf_ea: can't create new header: %s",
971                 fullpathname(path));
972             goto error;
973         }
974         ad->ad_mdp->adf_flags |= O_CREAT; /* mark as just created */
975         ad_flush(ad);
976         LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): created metadata EA", path);
977     }
978
979     /* TODO: ad_rlen calculation */
980     ad->ad_rlen = 0;
981
982     return 0;
983
984 error:
985     if (ad_meta_fileno(ad) != -1) {
986         close(ad_meta_fileno(ad));
987         ad_meta_fileno(ad) = -1;
988         ad->ad_mdp->adf_refcount = 0;
989     }
990     return ad_error(ad, adflags);
991 }
992
993 static int ad_open_hf(const char *path, int adflags, int mode, struct adouble *ad)
994 {
995     int ret = 0;
996
997     LOG(log_debug, logtype_default, "ad_open_hf(\"%s\", %04o)", path, mode);
998
999     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
1000     ad->ad_rlen = 0;
1001
1002     switch (ad->ad_vers) {
1003     case AD_VERSION2:
1004         ret = ad_open_hf_v2(path, adflags, mode, ad);
1005         break;
1006     case AD_VERSION_EA:
1007         ret = ad_open_hf_ea(path, adflags, mode, ad);
1008         break;
1009     default:
1010         ret = -1;
1011         break;
1012     }
1013
1014     if (ret != 0) {
1015         return ad_error(ad, adflags);
1016     }
1017     return ret;
1018 }
1019
1020
1021 /*!
1022  * Open ressource fork
1023  *
1024  * Only for adouble:ea, a nullop otherwise because adouble:v2 has the ressource fork as part
1025  * of the adouble file which is openend by ADFLAGS_HF.
1026  */
1027 static int ad_open_rf(const char *path, int adflags, int mode, struct adouble *ad)
1028 {
1029     EC_INIT;
1030     int oflags;
1031     int closeflags = adflags & (ADFLAGS_DF | ADFLAGS_HF);
1032     ssize_t rlen;
1033 #ifndef HAVE_EAFD
1034     const char *rfpath;
1035     struct stat st;
1036 #endif
1037
1038     if (ad->ad_vers != AD_VERSION_EA)
1039         return 0;
1040
1041     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\", %04o)", path, mode);
1042
1043     oflags = O_NOFOLLOW | (ad2openflags(adflags) & ~O_CREAT);
1044
1045     if (ad_reso_fileno(ad) != -1) {
1046         /* the file is already open, but we want write access: */
1047         if ((adflags & ADFLAGS_RDWR)
1048             /* and it was already denied: */
1049             && (ad->ad_rfp->adf_flags & O_RDONLY)) {
1050             errno = EACCES;
1051             return -1;
1052         }
1053         ad->ad_rfp->adf_flags &= ~( O_TRUNC | O_CREAT );
1054         ad->ad_rfp->adf_refcount++;
1055         return 0;
1056     }
1057 #ifdef HAVE_EAFD
1058     if ((ad_reso_fileno(ad) = sys_getxattrfd(path, oflags)) == -1) {
1059         if (!(adflags & ADFLAGS_CREATE))
1060             EC_FAIL;
1061         oflags |= O_CREAT;
1062         EC_NEG1_LOG( ad_reso_fileno(ad) = sys_getxattrfd(path, oflags, 0666) ); 
1063     }
1064 #else
1065     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags) );
1066     if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1067         if (!(adflags & ADFLAGS_CREATE))
1068             EC_FAIL;
1069         oflags |= O_CREAT;
1070         EC_NEG1_LOG( ad_reso_fileno(ad) = open(rfpath, oflags, mode) );
1071         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork: \"%s\"",
1072             path, rfpath);
1073     }
1074 #endif
1075
1076     ad->ad_rfp->adf_refcount = 1;
1077     ad->ad_rfp->adf_flags = oflags;
1078
1079 #ifndef HAVE_EAFD
1080     EC_ZERO_LOG( fstat(ad_reso_fileno(ad), &st) );
1081     if (ad->ad_rfp->adf_flags & O_CREAT) {
1082         /* This is a new adouble header file, create it */
1083         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, initializing: \"%s\"",
1084             path, rfpath);
1085 //        EC_NEG1_LOG( new_ad_header(ad, rfpath, &st, adflags) );
1086         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, flushing: \"%s\"",
1087             path, rfpath);
1088         ad_flush(ad);
1089     } else {
1090         /* Read the adouble header */
1091         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): reading adouble rfork: \"%s\"",
1092             path, rfpath);
1093         EC_NEG1_LOG( ad_header_read_osx(NULL, ad, &st) );
1094     }
1095 #endif
1096
1097 EC_CLEANUP:
1098     if (ret != 0) {
1099         if (ad_reso_fileno(ad) != -1) {
1100             close(ad_reso_fileno(ad));
1101             ad_reso_fileno(ad) = -1;
1102             ad->ad_rfp->adf_refcount = 0;
1103         }
1104         int err = errno;
1105         (void)ad_close(ad, closeflags);
1106         errno = err;
1107         ad->ad_rlen = 0;
1108     }
1109
1110     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): END", path);
1111
1112     EC_EXIT;
1113 }
1114
1115 /***********************************************************************************
1116  * API functions
1117  ********************************************************************************* */
1118
1119 const char *ad_path_ea( const char *path, int adflags _U_)
1120 {
1121     return path;
1122 }
1123
1124 const char *ad_path_osx(const char *path, int adflags _U_)
1125 {
1126     static char pathbuf[ MAXPATHLEN + 1];
1127     char    c, *slash, buf[MAXPATHLEN + 1];
1128
1129     if (!strcmp(path,".")) {
1130         /* fixme */
1131         getcwd(buf, MAXPATHLEN);
1132     }
1133     else {
1134         strlcpy(buf, path, MAXPATHLEN +1);
1135     }
1136     if (NULL != ( slash = strrchr( buf, '/' )) ) {
1137         c = *++slash;
1138         *slash = '\0';
1139         strlcpy( pathbuf, buf, MAXPATHLEN +1);
1140         *slash = c;
1141     } else {
1142         pathbuf[ 0 ] = '\0';
1143         slash = buf;
1144     }
1145     strlcat( pathbuf, "._", MAXPATHLEN  +1);
1146     strlcat( pathbuf, slash, MAXPATHLEN +1);
1147     return pathbuf;
1148 }
1149
1150 /*
1151  * Put the .AppleDouble where it needs to be:
1152  *
1153  *      /   a/.AppleDouble/b
1154  *  a/b
1155  *      \   b/.AppleDouble/.Parent
1156  *
1157  * FIXME: should do something for pathname > MAXPATHLEN
1158  */
1159 const char *ad_path( const char *path, int adflags)
1160 {
1161     static char pathbuf[ MAXPATHLEN + 1];
1162     const char *slash;
1163     size_t  l ;
1164
1165     if ( adflags & ADFLAGS_DIR ) {
1166         l = strlcpy( pathbuf, path, sizeof(pathbuf));
1167
1168         if ( l && l < MAXPATHLEN) {
1169             pathbuf[l++] = '/';
1170         }
1171         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
1172     } else {
1173         if (NULL != ( slash = strrchr( path, '/' )) ) {
1174             slash++;
1175             l = slash - path;
1176             /* XXX we must return NULL here and test in the caller */
1177             if (l > MAXPATHLEN)
1178                 l = MAXPATHLEN;
1179             memcpy( pathbuf, path, l);
1180         } else {
1181             l = 0;
1182             slash = path;
1183         }
1184         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
1185         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
1186     }
1187
1188     return( pathbuf );
1189 }
1190
1191 /* -------------------------
1192  * Support inherited protection modes for AppleDouble files.  The supplied
1193  * mode is ANDed with the parent directory's mask value in lieu of "umask",
1194  * and that value is returned.
1195  */
1196 char *ad_dir(const char *path)
1197 {
1198     static char     modebuf[ MAXPATHLEN + 1];
1199     char        *slash;
1200     /*
1201      * For a path with directories in it, remove the final component
1202      * (path or subdirectory name) to get the name we want to stat.
1203      * For a path which is just a filename, use "." instead.
1204      */
1205     slash = strrchr( path, '/' );
1206     if (slash) {
1207         size_t len;
1208
1209         len = slash - path;
1210         if (len >= MAXPATHLEN) {
1211             errno = ENAMETOOLONG;
1212             return NULL;  /* can't do it */
1213         }
1214         memcpy( modebuf, path, len );
1215         modebuf[len] = '\0';
1216         /* is last char a '/' ? */
1217         if (slash[1] == 0) {
1218             slash = modebuf+ len;
1219             /* remove them */
1220             while (modebuf < slash && slash[-1] == '/') {
1221                 --slash;
1222             }
1223             if (modebuf == slash) {
1224                 goto use_cur;
1225             }
1226             *slash = '\0';
1227             while (modebuf < slash && *slash != '/') {
1228                 --slash;
1229             }
1230             if (modebuf == slash) {
1231                 goto use_cur;
1232             }
1233             *slash = '\0';      /* remove pathname component */
1234         }
1235         return modebuf;
1236     }
1237 use_cur:
1238     modebuf[0] = '.';   /* use current directory */
1239     modebuf[1] = '\0';
1240     return modebuf;
1241 }
1242
1243 int ad_setfuid(const uid_t id)
1244 {
1245     default_uid = id;
1246     return 0;
1247 }
1248
1249 /* ---------------- */
1250 uid_t ad_getfuid(void)
1251 {
1252     return default_uid;
1253 }
1254
1255 /* ----------------
1256    stat path parent directory
1257 */
1258 int ad_stat(const char *path, struct stat *stbuf)
1259 {
1260     char *p;
1261
1262     p = ad_dir(path);
1263     if (!p)
1264         return -1;
1265     return lstat( p, stbuf );
1266 }
1267
1268 /* ----------------
1269    return access right of path parent directory
1270 */
1271 int ad_mode( const char *path, mode_t mode)
1272 {
1273     struct stat     stbuf;
1274     ad_mode_st(path, &mode, &stbuf);
1275     return mode;
1276 }
1277
1278 /*
1279  * Use mkdir() with mode bits taken from ad_mode().
1280  */
1281 int ad_mkdir( const char *path, mode_t mode)
1282 {
1283     int ret;
1284     int st_invalid;
1285     struct stat stbuf;
1286
1287     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
1288         path, mode, getcwdpath());
1289
1290     st_invalid = ad_mode_st(path, &mode, &stbuf);
1291     ret = mkdir( path, mode );
1292     if (ret || st_invalid)
1293         return ret;
1294     ad_chown(path, &stbuf);
1295
1296     return ret;
1297 }
1298
1299 static void ad_init_func(struct adouble *ad)
1300 {
1301     switch (ad->ad_vers) {
1302     case AD_VERSION2:
1303         ad->ad_ops = &ad_adouble;
1304         ad->ad_rfp = &ad->ad_resource_fork;
1305         ad->ad_mdp = &ad->ad_resource_fork;
1306         break;
1307     case AD_VERSION_EA:
1308         ad->ad_ops = &ad_adouble_ea;
1309         ad->ad_rfp = &ad->ad_resource_fork;
1310         ad->ad_mdp = &ad->ad_data_fork;
1311         break;
1312     default:
1313         AFP_PANIC("ad_init: unknown AD version");
1314     }
1315
1316
1317     ad_data_fileno(ad) = -1;
1318     ad_reso_fileno(ad) = -1;
1319     ad_meta_fileno(ad) = -1;
1320     ad->ad_refcount = 1;
1321     return;
1322 }
1323
1324 void ad_init_old(struct adouble *ad, int flags, int options)
1325 {
1326     memset(ad, 0, sizeof(struct adouble));
1327     ad->ad_vers = flags;
1328     ad->ad_options = options;
1329     ad_init_func(ad);
1330 }
1331
1332 void ad_init(struct adouble *ad, const struct vol * restrict vol)
1333 {
1334     memset(ad, 0, sizeof(struct adouble));
1335     ad->ad_vers = vol->v_adouble;
1336     ad->ad_options = vol->v_ad_options;
1337     ad_init_func(ad);
1338 }
1339
1340 /*!
1341  * Open data-, metadata(header)- or ressource fork
1342  *
1343  * ad_open(struct adouble *ad, const char *path, int adflags, int flags)
1344  * ad_open(struct adouble *ad, const char *path, int adflags, int flags, mode_t mode)
1345  *
1346  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1347  * @code
1348  *      struct adoube ad;
1349  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1350  * @endcode
1351  *
1352  * Open a files data fork, metadata fork or ressource fork.
1353  *
1354  * @param ad        (rw) pointer to struct adouble
1355  * @param path      (r)  Path to file or directory
1356  * @param adflags   (r)  Flags specifying which fork to open, can be or'd:
1357  *                         ADFLAGS_DF:        open data fork
1358  *                         ADFLAGS_RF:        open ressource fork
1359  *                         ADFLAGS_HF:        open header (metadata) file
1360  *                         ADFLAGS_NOHF:      it's not an error if header file couldn't be created
1361  *                         ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags
1362  *
1363  *                       Access mode for the forks:
1364  *                         ADFLAGS_RDONLY:    open read only
1365  *                         ADFLAGS_RDWR:      open read write
1366  *
1367  *                       Creation flags:
1368  *                         ADFLAGS_CREATE:    create if not existing
1369  *                         ADFLAGS_TRUNC:     truncate
1370  *
1371  *                       Special flags:
1372  *                         ADFLAGS_CHECK_OF:  check for open forks from us and other afpd's
1373  *                         ADFLAGS_SETSHRMD:  this adouble struct will be used to set sharemode locks.
1374  *                                            This basically results in the files being opened RW instead of RDONLY.
1375  * @param mode      (r)  mode used with O_CREATE
1376  *
1377  * The open mode flags (rw vs ro) have to take into account all the following requirements:
1378  * - we remember open fds for files because me must avoid a single close releasing fcntl locks for other
1379  *   fds of the same file
1380  *
1381  * @returns 0 on success, any other value indicates an error
1382  */
1383 int ad_open(struct adouble *ad, const char *path, int adflags, ...)
1384 {
1385     EC_INIT;
1386     va_list args;
1387     mode_t mode = 0;
1388
1389     LOG(log_debug, logtype_default, "ad_open(\"%s\", %s)",
1390         fullpathname(path), adflags2logstr(adflags));
1391
1392     if (adflags & ADFLAGS_CHECK_OF)
1393         /* Checking for open forks requires sharemode lock support (ie RDWR instead of RDONLY) */
1394         adflags |= ADFLAGS_SETSHRMD;
1395
1396     if ((ad->ad_vers == AD_VERSION_EA) && (adflags & ADFLAGS_SETSHRMD))
1397         /* adouble:ea sets sharemode locks on the datafork */
1398         adflags |= ADFLAGS_DF;
1399
1400     if (ad->ad_inited != AD_INITED) {
1401         ad->ad_adflags = adflags;
1402         ad->ad_inited = AD_INITED;
1403     } else {
1404         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1405         if (ad->ad_resource_fork.adf_refcount > 0)
1406             ad->ad_open_forks |= ATTRBIT_ROPEN;
1407     }
1408
1409     va_start(args, adflags);
1410     if (adflags & ADFLAGS_CREATE)
1411         mode = va_arg(args, mode_t);
1412     va_end(args);
1413
1414     if (adflags & ADFLAGS_DF) {
1415         EC_ZERO( ad_open_df(path, adflags, mode, ad) );
1416         ad->ad_adflags |= ADFLAGS_DF;
1417     }
1418
1419     if (adflags & ADFLAGS_HF) {
1420         EC_ZERO( ad_open_hf(path, adflags, mode, ad) );
1421         ad->ad_adflags |= ADFLAGS_HF;
1422     }
1423
1424     if (adflags & ADFLAGS_RF) {
1425         EC_ZERO( ad_open_rf(path, adflags, mode, ad) );
1426         ad->ad_adflags |= ADFLAGS_RF;
1427     }
1428
1429     if (adflags & ADFLAGS_CHECK_OF) {
1430         ad->ad_open_forks |= ad_openforks(ad, ad->ad_open_forks);
1431     }
1432
1433 EC_CLEANUP:
1434     return ret;
1435 }
1436
1437 /*!
1438  * @brief open metadata, possibly as root
1439  *
1440  * Return only metadata but try very hard ie at first try as user, then try as root.
1441  *
1442  * @param name  name of file/dir
1443  * @param flags ADFLAGS_DIR: name is a directory \n
1444  *              ADFLAGS_CHECK_OF: test if name is open by us or another afpd process
1445  *
1446  * @param adp   pointer to struct adouble
1447  */
1448 int ad_metadata(const char *name, int flags, struct adouble *adp)
1449 {
1450     uid_t uid;
1451     int   ret, err, oflags;
1452
1453     /* Sanitize flags */
1454     oflags = (flags & (ADFLAGS_CHECK_OF | ADFLAGS_DIR)) | ADFLAGS_HF | ADFLAGS_RDONLY;    
1455
1456     if ((ret = ad_open(adp, name, oflags)) < 0 && errno == EACCES) {
1457         uid = geteuid();
1458         if (seteuid(0)) {
1459             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1460             errno = EACCES;
1461             return -1;
1462         }
1463         /* we are root open read only */
1464         ret = ad_open(adp, name, oflags);
1465         err = errno;
1466         if ( seteuid(uid) < 0) {
1467             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1468             exit(EXITERR_SYS);
1469         }
1470         errno = err;
1471     }
1472
1473     return ret;
1474 }
1475
1476 /*
1477  * @brief openat like wrapper for ad_metadata
1478  */
1479 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1480 {
1481     int ret = 0;
1482     int cwdfd = -1;
1483
1484     if (dirfd != -1) {
1485         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1486             ret = -1;
1487             goto exit;
1488         }
1489     }
1490
1491     if (ad_metadata(name, flags, adp) < 0) {
1492         ret = -1;
1493         goto exit;
1494     }
1495
1496     if (dirfd != -1) {
1497         if (fchdir(cwdfd) != 0) {
1498             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1499             exit(EXITERR_SYS);
1500         }
1501     }
1502
1503 exit:
1504     if (cwdfd != -1)
1505         close(cwdfd);
1506
1507     return ret;
1508
1509 }
1510
1511 int ad_refresh(const char *path, struct adouble *ad)
1512 {
1513     switch (ad->ad_vers) {
1514     case AD_VERSION2:
1515         if (ad_meta_fileno(ad) == -1)
1516             return -1;
1517         return ad->ad_ops->ad_header_read(NULL, ad, NULL);
1518         break;
1519     case AD_VERSION_EA:
1520 #ifdef HAVE_EAFD
1521         if (AD_META_OPEN(ad)) {
1522             if (ad_data_fileno(ad) == -1)
1523                 return -1;
1524             // TODO: read meta EA
1525         }
1526
1527         if (AD_RSRC_OPEN(ad)) {
1528             if (ad_reso_fileno(ad) == -1)
1529                 return -1;
1530             ssize_t len;
1531             if ((len = fstat(ad_reso_fileno(ad))) == -1)
1532                 return -1;
1533             ad->ad_rlen = len;
1534         }
1535 #else
1536         if (AD_META_OPEN(ad)) {
1537             if (ad_data_fileno(ad) == -1)
1538                 return -1;
1539             // TODO: read meta EA
1540         }
1541         if (AD_RSRC_OPEN(ad)) {
1542             if (ad_reso_fileno(ad) == -1)
1543                 return -1;
1544             if (ad_header_read_osx(path, ad, NULL) < 0)
1545                 return -1;
1546         }
1547 #endif
1548         return ad->ad_ops->ad_header_read(path, ad, NULL);
1549         break;
1550     default:
1551         return -1;
1552         break;
1553     }
1554
1555 }
1556
1557 int ad_openat(struct adouble  *ad,
1558               int dirfd,  /* dir fd openat like */
1559               const char *path,
1560               int adflags, ...)
1561 {
1562     EC_INIT;
1563     int cwdfd = -1;
1564     va_list args;
1565     mode_t mode;
1566
1567     if (dirfd != -1) {
1568         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0))
1569             EC_FAIL;
1570     }
1571
1572     va_start(args, adflags);
1573     if (adflags & ADFLAGS_CREATE)
1574         mode = va_arg(args, mode_t);
1575     va_end(args);
1576
1577     EC_NEG1( ad_open(ad, path, adflags, mode) );
1578
1579     if (dirfd != -1) {
1580         if (fchdir(cwdfd) != 0) {
1581             AFP_PANIC("ad_openat: cant chdir back");
1582         }
1583     }
1584
1585 EC_CLEANUP:
1586     if (cwdfd != -1)
1587         close(cwdfd);
1588
1589     return ret;
1590 }