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