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