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