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