]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Convert afp_moveandrename and all called funcs to XXXat semantics if available
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * $Id: ad_open.c,v 1.72 2010-03-12 15:16:49 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 //FIXME!
1018     return lstat( 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 = lchown( 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         ad->ad_data_fork.adf_syml=0;
1269     }
1270     else {
1271         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1272         /* XXX not true if we have a meta data fork ? */
1273         if ((ad->ad_resource_fork.adf_refcount > ad->ad_data_fork.adf_refcount))
1274             ad->ad_open_forks |= ATTRBIT_ROPEN;
1275     }
1276
1277     if ((adflags & ADFLAGS_DF)) {
1278         if (ad_data_fileno(ad) == -1) {
1279             hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
1280             admode = mode;
1281             if ((oflags & O_CREAT)) {
1282                 st_invalid = ad_mode_st(path, &admode, &st_dir);
1283                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1284                     admode = mode;
1285                 }
1286             }
1287                 
1288             ad->ad_data_fork.adf_fd =open( path, hoflags | O_NOFOLLOW, admode );
1289             
1290             if (ad->ad_data_fork.adf_fd < 0 ) {
1291                 if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
1292                     hoflags = oflags;
1293                     ad->ad_data_fork.adf_fd = open( path, hoflags | O_NOFOLLOW, admode );
1294                 }
1295                 if (ad->ad_data_fork.adf_fd < 0 && errno == ELOOP) {
1296                     int lsz;
1297
1298                     if (oflags != O_RDONLY)
1299                          return -1;
1300
1301                     ad->ad_data_fork.adf_syml = malloc(PATH_MAX+1);
1302                     lsz = readlink(path, ad->ad_data_fork.adf_syml, PATH_MAX);
1303                     if (lsz <= 0) {
1304                         free(ad->ad_data_fork.adf_syml);
1305                         return -1;
1306                     }
1307                     ad->ad_data_fork.adf_syml[lsz]=0;
1308                     ad->ad_data_fork.adf_syml = realloc(ad->ad_data_fork.adf_syml,lsz+1);
1309                     // XX
1310                     ad->ad_data_fork.adf_fd = 0;
1311                 }
1312             }
1313
1314             if ( ad->ad_data_fork.adf_fd < 0)
1315                 return -1;
1316
1317             AD_SET(ad->ad_data_fork.adf_off);
1318             ad->ad_data_fork.adf_flags = hoflags;
1319             if (!st_invalid) {
1320                 /* just created, set owner if admin (root) */
1321                 ad_chown(path, &st_dir);
1322             }
1323             adf_lock_init(&ad->ad_data_fork);
1324         }
1325         else {
1326             /* the file is already open... but */
1327             if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
1328                 !(ad->ad_data_fork.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
1329             {
1330                 errno = EACCES;
1331                 return -1;
1332             }
1333             /* FIXME
1334              * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
1335              * already open. Should we check for it? ie
1336              * O_EXCL --> error
1337              * O_TRUNC --> truncate the fork.
1338              * idem for ressource fork.
1339              */
1340         }
1341         open_df = ADFLAGS_DF;
1342         ad->ad_data_fork.adf_refcount++;
1343     }
1344
1345     if (!(adflags & ADFLAGS_HF))
1346         return 0;
1347
1348     /* ****************************************** */
1349
1350     if (ad_meta_fileno(ad) != -1) { /* the file is already open */
1351         if ((oflags & ( O_RDWR | O_WRONLY)) &&
1352             !(ad->ad_md->adf_flags & ( O_RDWR | O_WRONLY))) {
1353             if (open_df) {
1354                 /* don't call with ADFLAGS_HF because we didn't open ressource fork */
1355                 ad_close( ad, open_df );
1356             }
1357             errno = EACCES;
1358             return -1;
1359         }
1360         ad_refresh(ad);
1361         /* it's not new anymore */
1362         ad->ad_md->adf_flags &= ~( O_TRUNC | O_CREAT );
1363         ad->ad_md->adf_refcount++;
1364         goto sfm;
1365     }
1366
1367     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
1368     ad->ad_rlen = 0;
1369     ad_p = ad->ad_ops->ad_path( path, adflags );
1370
1371     hoflags = oflags & ~(O_CREAT | O_EXCL);
1372     if (!(adflags & ADFLAGS_RDONLY)) {
1373         hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
1374     }
1375     ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
1376     if (ad->ad_md->adf_fd < 0 ) {
1377         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
1378             hoflags = oflags & ~(O_CREAT | O_EXCL);
1379             ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
1380         }
1381     }
1382
1383     if ( ad->ad_md->adf_fd < 0 ) {
1384         if (errno == ENOENT && (oflags & O_CREAT) ) {
1385             /*
1386              * We're expecting to create a new adouble header file,
1387              * here.
1388              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
1389              */
1390             LOG(log_debug, logtype_default, "ad_open: creating new adouble file: %s/%s", getcwdpath(), ad_p);
1391             admode = mode;
1392             errno = 0;
1393             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1394             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1395                 admode = mode;
1396             }
1397             admode = ad_hf_mode(admode);
1398             if ((errno == ENOENT) && (ad->ad_flags != AD_VERSION2_OSX)) {
1399                 if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
1400                     return ad_error(ad, adflags);
1401                 }
1402                 admode = mode;
1403                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1404                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1405                     admode = mode;
1406                 }
1407                 admode = ad_hf_mode(admode);
1408             }
1409             /* retry with O_CREAT */
1410             ad->ad_md->adf_fd = open( ad_p, oflags,admode );
1411             if ( ad->ad_md->adf_fd < 0 ) {
1412                 return ad_error(ad, adflags);
1413             }
1414             ad->ad_md->adf_flags = oflags;
1415             /* just created, set owner if admin owner (root) */
1416             if (!st_invalid) {
1417                 ad_chown(ad_p, &st_dir);
1418             }
1419         }
1420         else {
1421             return ad_error(ad, adflags);
1422         }
1423     } else {
1424         ad->ad_md->adf_flags = hoflags;
1425         if (fstat(ad->ad_md->adf_fd, &st_meta) == 0 && st_meta.st_size == 0) {
1426             /* for 0 length files, treat them as new. */
1427             ad->ad_md->adf_flags |= O_TRUNC;
1428         } 
1429         else {
1430             /* we have valid data in st_meta stat structure, reused it
1431                in ad_header_read
1432             */
1433             pst = &st_meta;
1434         }
1435     }
1436     AD_SET(ad->ad_md->adf_off);
1437
1438     ad->ad_md->adf_refcount = 1;
1439     adf_lock_init(ad->ad_md);
1440     if ((ad->ad_md->adf_flags & ( O_TRUNC | O_CREAT ))) {
1441         /*
1442          * This is a new adouble header file. Initialize the structure,
1443          * instead of reading it.
1444          */
1445         if (new_rfork(path, ad, adflags) < 0) {
1446             int err = errno;
1447             /* the file is already deleted, perm, whatever, so return an error*/
1448             ad_close(ad, adflags);
1449             errno = err;
1450             return -1;
1451         }
1452         ad_flush(ad);
1453     } else {
1454         /* Read the adouble header in and parse it.*/
1455         if (ad->ad_ops->ad_header_read( ad , pst) < 0
1456             || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0)
1457         {
1458             int err = errno;
1459
1460             ad_close( ad, adflags );
1461             errno = err;
1462             return -1;
1463         }
1464     }
1465
1466     /* ****************************************** */
1467     /* open the resource fork if SFM */
1468 sfm:
1469     if (ad->ad_flags != AD_VERSION1_SFM) {
1470         return 0;
1471     }
1472
1473     if ((adflags & ADFLAGS_DIR)) {
1474         /* no resource fork for directories / volumes XXX it's false! */
1475         return 0;
1476     }
1477
1478     /* untrue yet but ad_close will decremente it*/
1479     ad->ad_resource_fork.adf_refcount++;
1480
1481     if (ad_reso_fileno(ad) != -1) { /* the file is already open */
1482         if ((oflags & ( O_RDWR | O_WRONLY)) &&
1483             !(ad->ad_resource_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
1484
1485             ad_close( ad, open_df | ADFLAGS_HF);
1486             errno = EACCES;
1487             return -1;
1488         }
1489         return 0;
1490     }
1491
1492     ad_p = ad->ad_ops->ad_path( path, ADFLAGS_RF );
1493
1494     admode = mode;
1495     st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
1496
1497     if ((ad->ad_options & ADVOL_UNIXPRIV)) {
1498         admode = mode;
1499     }
1500
1501     hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
1502     ad->ad_resource_fork.adf_fd = open( ad_p, hoflags, admode );
1503
1504     if (ad->ad_resource_fork.adf_fd < 0 ) {
1505         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
1506             hoflags = oflags;
1507             ad->ad_resource_fork.adf_fd =open( ad_p, hoflags, admode );
1508         }
1509     }
1510
1511     if ( ad->ad_resource_fork.adf_fd < 0) {
1512         int err = errno;
1513
1514         ad_close( ad, adflags );
1515         errno = err;
1516         return -1;
1517     }
1518     adf_lock_init(&ad->ad_resource_fork);
1519     AD_SET(ad->ad_resource_fork.adf_off);
1520     ad->ad_resource_fork.adf_flags = hoflags;
1521     if ((oflags & O_CREAT) && !st_invalid) {
1522         /* just created, set owner if admin (root) */
1523         ad_chown(ad_p, &st_dir);
1524     }
1525     else if (!fstat(ad->ad_resource_fork.adf_fd, &st_meta)) {
1526         ad->ad_rlen = st_meta.st_size;
1527     }
1528     return 0 ;
1529 }
1530
1531 /*!
1532  * @brief open metadata, possibly as root
1533  *
1534  * Return only metadata but try very hard ie at first try as user, then try as root.
1535  *
1536  * @param name  name of file/dir
1537  * @param flags ADFLAGS_DIR: name is a directory \n
1538  *              ADFLAGS_CREATE: force creation of header file, but only as user, not as root\n
1539  *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
1540  *
1541  * @param adp   pointer to struct adouble
1542  *
1543  * @note caller MUST pass ADFLAGS_DIR for directories. Whether ADFLAGS_CREATE really creates
1544  *       a adouble file depends on various other volume options, eg. ADVOL_CACHE
1545  */
1546 int ad_metadata(const char *name, int flags, struct adouble *adp)
1547 {
1548     uid_t uid;
1549     int   ret, err, dir;
1550     int   create = O_RDONLY;
1551
1552     dir = flags & ADFLAGS_DIR;
1553
1554     /* Check if we shall call ad_open with O_CREAT */
1555     if ( (adp->ad_options & ADVOL_CACHE)
1556          && ! (adp->ad_options & ADVOL_NOADOUBLE)
1557          && (flags & ADFLAGS_CREATE) ) {
1558         create = O_CREAT | O_RDWR;
1559     }
1560     if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
1561         uid = geteuid();
1562         if (seteuid(0)) {
1563             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1564             errno = EACCES;
1565             return -1;
1566         }
1567         /* we are root open read only */
1568         ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
1569         err = errno;
1570         if ( seteuid(uid) < 0) {
1571             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1572             exit(EXITERR_SYS);
1573         }
1574         errno = err;
1575     }
1576
1577     if (!ret && (ADFLAGS_OPENFORKS & flags)) {
1578         /*
1579           we need to check if the file is open by another process.
1580           it's slow so we only do it if we have to:
1581           - it's requested.
1582           - we don't already have the answer!
1583         */
1584         adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
1585     }
1586     return ret;
1587 }
1588
1589 /*
1590  * @brief openat like wrapper for ad_metadata
1591  */
1592 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1593 {
1594     int ret = 0;
1595     int cwdfd = -1;
1596
1597     if (dirfd != -1) {
1598         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1599             ret = -1;
1600             goto exit;
1601         }
1602     }
1603
1604     if (ad_metadata(name, flags, adp) < 0) {
1605         ret = -1;
1606         goto exit;
1607     }
1608
1609     if (dirfd != -1) {
1610         if (fchdir(cwdfd) != 0) {
1611             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1612             exit(EXITERR_SYS);
1613         }
1614     }
1615
1616 exit:
1617     if (cwdfd != -1)
1618         close(cwdfd);
1619
1620     return ret;
1621
1622 }
1623
1624 /* ----------------------------------- */
1625 static int new_rfork(const char *path, struct adouble *ad, int adflags)
1626 {
1627     const struct entry  *eid;
1628     u_int16_t           ashort;
1629     struct stat         st;
1630
1631     ad->ad_magic = AD_MAGIC;
1632     ad->ad_version = ad->ad_flags & 0x0f0000;
1633     if (!ad->ad_version) {
1634         ad->ad_version = AD_VERSION;
1635     }
1636
1637     memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
1638     memset(ad->ad_data, 0, sizeof(ad->ad_data));
1639
1640 #if AD_VERSION == AD_VERSION2
1641     if (ad->ad_flags == AD_VERSION2)
1642         eid = entry_order2;
1643     else if (ad->ad_flags == AD_VERSION2_OSX)
1644         eid = entry_order_osx;
1645     else  if (ad->ad_flags == AD_VERSION1_SFM) {
1646         ad->ad_magic = SFM_MAGIC;
1647         eid = entry_order_sfm;
1648     }
1649     else
1650 #endif
1651         eid = entry_order1;
1652
1653     while (eid->id) {
1654         ad->ad_eid[eid->id].ade_off = eid->offset;
1655         ad->ad_eid[eid->id].ade_len = eid->len;
1656         eid++;
1657     }
1658
1659     /* put something sane in the directory finderinfo */
1660     if ((adflags & ADFLAGS_DIR)) {
1661         /* set default view */
1662         ashort = htons(FINDERINFO_CLOSEDVIEW);
1663         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF,
1664                &ashort, sizeof(ashort));
1665     } else {
1666         /* set default creator/type fields */
1667         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
1668         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
1669     }
1670
1671     /* make things invisible */
1672     if ((ad->ad_options & ADVOL_INVDOTS) && !(adflags & ADFLAGS_CREATE) &&
1673         (*path == '.') && strcmp(path, ".") && strcmp(path, ".."))
1674     {
1675         ashort = htons(ATTRBIT_INVISIBLE);
1676         ad_setattr(ad, ashort);
1677         ashort = htons(FINDERINFO_INVISIBLE);
1678         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
1679     }
1680
1681     if (lstat(path, &st) < 0) {
1682         return -1;
1683     }
1684
1685     /* put something sane in the date fields */
1686     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
1687     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
1688     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
1689     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
1690     return 0;
1691 }
1692
1693 /* to do this with mmap, we need the hfs fs to understand how to mmap
1694    header files. */
1695 int ad_refresh(struct adouble *ad)
1696 {
1697
1698     if (ad_meta_fileno(ad) < 0)
1699         return -1;
1700
1701     return ad->ad_ops->ad_header_read(ad, NULL);
1702 }
1703
1704 int ad_openat(int dirfd,  /* dir fd openat like */
1705               const char *path,
1706               int adflags,
1707               int oflags,
1708               int mode,
1709               struct adouble  *ad)
1710 {
1711     int ret = 0;
1712     int cwdfd = -1;
1713
1714     if (dirfd != -1) {
1715         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1716             ret = -1;
1717             goto exit;
1718         }
1719     }
1720
1721     if (ad_open(path, adflags, oflags, mode, ad) < 0) {
1722         ret = -1;
1723         goto exit;
1724     }
1725
1726     if (dirfd != -1) {
1727         if (fchdir(cwdfd) != 0) {
1728             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1729             exit(EXITERR_SYS);
1730         }
1731     }
1732
1733 exit:
1734     if (cwdfd != -1)
1735         close(cwdfd);
1736
1737     return ret;
1738 }