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