]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Fix open flags
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu)
3  * Copyright (c) 1990,1991 Regents of The University of Michigan.
4  * Copyright (c) 2010 Frank Lahm
5  *
6  * All Rights Reserved.
7  *
8  * Permission to use, copy, modify, and distribute this software and
9  * its documentation for any purpose and without fee is hereby granted,
10  * provided that the above copyright notice appears in all copies and
11  * that both that copyright notice and this permission notice appear
12  * in supporting documentation, and that the name of The University
13  * of Michigan not be used in advertising or publicity pertaining to
14  * distribution of the software without specific, written prior
15  * permission. This software is supplied as is without expressed or
16  * implied warranties of any kind.
17  *
18  *  Research Systems Unix Group
19  *  The University of Michigan
20  *  c/o Mike Clark
21  *  535 W. William Street
22  *  Ann Arbor, Michigan
23  *  +1-313-763-0525
24  *  netatalk@itd.umich.edu
25  *
26  */
27
28 /*!
29  * @file
30  * Part of Netatalk's AppleDouble implementatation
31  * @sa include/atalk/adouble.h
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif /* HAVE_CONFIG_H */
37
38 #include <errno.h>
39 #include <sys/param.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <stdarg.h>
43 #include <arpa/inet.h>
44
45 #include <atalk/logger.h>
46 #include <atalk/adouble.h>
47 #include <atalk/util.h>
48 #include <atalk/ea.h>
49 #include <atalk/bstrlib.h>
50 #include <atalk/bstradd.h>
51 #include <atalk/compat.h>
52 #include <atalk/errchk.h>
53 #include <atalk/volume.h>
54
55 #include "ad_lock.h"
56
57 #define ADEDOFF_MAGIC        (0)
58 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
59 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
60 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
61
62 /* initial lengths of some of the fields */
63 #define ADEDLEN_INIT     0
64
65 /* i stick things in a slightly different order than their eid order in
66  * case i ever want to separate RootInfo behaviour from the rest of the
67  * stuff. */
68
69 /* ad:v2 */
70 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
71 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
72 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
73 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
74 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
75 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
76 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
77 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
78 #define ADEDOFF_PRIVDEV      (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
79 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
80 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
81 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
82 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
83
84 /* ad:ea */
85 #define ADEDOFF_FINDERI_EA    (AD_HEADER_LEN + ADEID_NUM_EA * AD_ENTRY_LEN)
86 #define ADEDOFF_COMMENT_EA    (ADEDOFF_FINDERI_EA + ADEDLEN_FINDERI)
87 #define ADEDOFF_FILEDATESI_EA (ADEDOFF_COMMENT_EA + ADEDLEN_COMMENT)
88 #define ADEDOFF_AFPFILEI_EA   (ADEDOFF_FILEDATESI_EA + ADEDLEN_FILEDATESI)
89 #define ADEDOFF_PRIVID_EA     (ADEDOFF_AFPFILEI_EA + ADEDLEN_AFPFILEI)
90
91 /* this is to prevent changing timezones from causing problems with
92    localtime volumes. the screw-up is 30 years. we use a delta of 5 years */
93 #define TIMEWARP_DELTA 157680000
94
95 struct entry {
96     uint32_t id, offset, len;
97 };
98
99 /* --------------------------- */
100 static uid_t default_uid = -1;
101
102 /* Forward declarations */
103 static int ad_mkrf(const char *path);
104 static int ad_header_read(const char *path, struct adouble *ad, struct stat *hst);
105 static int ad_header_upgrade(struct adouble *ad, const char *name);
106
107 static int ad_mkrf_ea(const char *path);
108 static int ad_header_read_ea(const char *path, struct adouble *ad, struct stat *hst);
109 static int ad_header_upgrade_ea(struct adouble *ad, const char *name);
110 static int ad_reso_size(const char *path, int adflags, struct adouble *ad);
111 static int ad_mkrf_osx(const char *path);
112
113
114 static struct adouble_fops ad_adouble = {
115     &ad_path,
116     &ad_mkrf,
117     &ad_rebuild_adouble_header,
118     &ad_header_read,
119     &ad_header_upgrade,
120 };
121
122 static struct adouble_fops ad_adouble_ea = {
123 #ifdef HAVE_EAFD
124     &ad_path_ea,
125     &ad_mkrf_ea,
126 #else
127     &ad_path_osx,
128     &ad_mkrf_osx,
129 #endif
130     &ad_rebuild_adouble_header,
131     &ad_header_read_ea,
132     &ad_header_upgrade_ea,
133 };
134
135 static struct adouble_fops ad_osx = {
136     &ad_path_osx,
137     &ad_mkrf_osx,
138     &ad_rebuild_adouble_header,
139     &ad_header_read,
140     &ad_header_upgrade,
141 };
142
143 static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
144     {ADEID_NAME,        ADEDOFF_NAME_V2,     ADEDLEN_INIT},
145     {ADEID_COMMENT,     ADEDOFF_COMMENT_V2,  ADEDLEN_INIT},
146     {ADEID_FILEDATESI,  ADEDOFF_FILEDATESI,  ADEDLEN_FILEDATESI},
147     {ADEID_FINDERI,     ADEDOFF_FINDERI_V2,  ADEDLEN_FINDERI},
148     {ADEID_DID,         ADEDOFF_DID,         ADEDLEN_DID},
149     {ADEID_AFPFILEI,    ADEDOFF_AFPFILEI,    ADEDLEN_AFPFILEI},
150     {ADEID_SHORTNAME,   ADEDOFF_SHORTNAME,   ADEDLEN_INIT},
151     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
152     {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV,     ADEDLEN_INIT},
153     {ADEID_PRIVINO,     ADEDOFF_PRIVINO,     ADEDLEN_INIT},
154     {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN,     ADEDLEN_INIT},
155     {ADEID_PRIVID,      ADEDOFF_PRIVID,      ADEDLEN_INIT},
156     {ADEID_RFORK,       ADEDOFF_RFORK_V2,    ADEDLEN_INIT},
157     {0, 0, 0}
158 };
159
160 /* Using Extended Attributes */
161 static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
162     {ADEID_FINDERI,    ADEDOFF_FINDERI_EA,    ADEDLEN_FINDERI},
163     {ADEID_COMMENT,    ADEDOFF_COMMENT_EA,    ADEDLEN_INIT},
164     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_EA, ADEDLEN_FILEDATESI},
165     {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_EA,   ADEDLEN_AFPFILEI},
166     {ADEID_PRIVID,     ADEDOFF_PRIVID_EA,     ADEDLEN_INIT},
167     {0, 0, 0}
168 };
169
170 /* fallback for EAs */
171 static const struct entry entry_order_osx[ADEID_NUM_OSX +1] = {
172     {ADEID_FINDERI, ADEDOFF_FINDERI_OSX, ADEDLEN_FINDERI},
173     {ADEID_RFORK, ADEDOFF_RFORK_OSX, ADEDLEN_INIT},
174     {0, 0, 0}
175 };
176
177 #define ADFLAGS2LOGSTRBUFSIZ 128
178 const char *adflags2logstr(int adflags)
179 {
180     int first = 1;
181     static char buf[ADFLAGS2LOGSTRBUFSIZ];
182
183     buf[0] = 0;
184
185     if (adflags & ADFLAGS_DF) {
186         strlcat(buf, "DF", ADFLAGS2LOGSTRBUFSIZ);
187         first = 0;
188     }
189     if (adflags & ADFLAGS_RF) {
190         if (!first)
191             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
192         strlcat(buf, "RF", ADFLAGS2LOGSTRBUFSIZ);
193         first = 0;
194     }
195     if (adflags & ADFLAGS_NORF) {
196         if (!first)
197             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
198         strlcat(buf, "NORF", ADFLAGS2LOGSTRBUFSIZ);
199         first = 0;
200     }
201     if (adflags & ADFLAGS_HF) {
202         if (!first)
203             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
204         strlcat(buf, "HF", ADFLAGS2LOGSTRBUFSIZ);
205         first = 0;
206     }
207     if (adflags & ADFLAGS_NOHF) {
208         if (!first)
209             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
210         strlcat(buf, "NOHF", ADFLAGS2LOGSTRBUFSIZ);
211         first = 0;
212     }
213     if (adflags & ADFLAGS_DIR) {
214         if (!first)
215             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
216         strlcat(buf, "DIR", ADFLAGS2LOGSTRBUFSIZ);
217         first = 0;
218     }
219     if (adflags & ADFLAGS_CHECK_OF) {
220         if (!first)
221             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
222         strlcat(buf, "OF", ADFLAGS2LOGSTRBUFSIZ);
223         first = 0;
224     }
225     if (adflags & ADFLAGS_SETSHRMD) {
226         if (!first)
227             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
228         strlcat(buf, "SHRMD", ADFLAGS2LOGSTRBUFSIZ);
229         first = 0;
230     }
231     if (adflags & ADFLAGS_RDWR) {
232         if (!first)
233             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
234         strlcat(buf, "O_RDWR", ADFLAGS2LOGSTRBUFSIZ);
235         first = 0;
236     }
237     if (adflags & ADFLAGS_RDONLY) {
238         if (!first)
239             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
240         strlcat(buf, "O_RDONLY", ADFLAGS2LOGSTRBUFSIZ);
241         first = 0;
242     }
243     if (adflags & ADFLAGS_CREATE) {
244         if (!first)
245             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
246         strlcat(buf, "O_CREAT", ADFLAGS2LOGSTRBUFSIZ);
247         first = 0;
248     }
249     if (adflags & ADFLAGS_EXCL) {
250         if (!first)
251             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
252         strlcat(buf, "O_EXCL", ADFLAGS2LOGSTRBUFSIZ);
253         first = 0;
254     }
255     if (adflags & ADFLAGS_TRUNC) {
256         if (!first)
257             strlcat(buf, "|", ADFLAGS2LOGSTRBUFSIZ);
258         strlcat(buf, "O_TRUNC", ADFLAGS2LOGSTRBUFSIZ);
259         first = 0;
260     }
261
262     return buf;
263 }
264
265 #define OPENFLAGS2LOGSTRBUFSIZ 128
266 const char *openflags2logstr(int oflags)
267 {
268     int first = 1;
269     static char buf[OPENFLAGS2LOGSTRBUFSIZ];
270
271     buf[0] = 0;
272
273     if ((oflags & O_RDONLY) || (oflags == O_RDONLY)) {
274         strlcat(buf, "O_RDONLY", OPENFLAGS2LOGSTRBUFSIZ);
275         first = 0;
276     }
277     if (oflags & O_RDWR) {
278         if (!first)
279             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
280         strlcat(buf, "O_RDWR", OPENFLAGS2LOGSTRBUFSIZ);
281         first = 0;
282     }
283     if (oflags & O_CREAT) {
284         if (!first)
285             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
286         strlcat(buf, "O_CREAT", OPENFLAGS2LOGSTRBUFSIZ);
287         first = 0;
288     }
289     if (oflags & O_TRUNC) {
290         if (!first)
291             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
292         strlcat(buf, "O_TRUNC", OPENFLAGS2LOGSTRBUFSIZ);
293         first = 0;
294     }
295     if (oflags & O_EXCL) {
296         if (!first)
297             strlcat(buf, "|", OPENFLAGS2LOGSTRBUFSIZ);
298         strlcat(buf, "O_EXCL", OPENFLAGS2LOGSTRBUFSIZ);
299         first = 0;
300     }
301     return buf;
302 }    
303
304 static uint32_t get_eid(uint32_t eid)
305 {
306     if (eid <= 15)
307         return eid;
308     if (eid == AD_DEV)
309         return ADEID_PRIVDEV;
310     if (eid == AD_INO)
311         return ADEID_PRIVINO;
312     if (eid == AD_SYN)
313         return ADEID_PRIVSYN;
314     if (eid == AD_ID)
315         return ADEID_PRIVID;
316
317     return 0;
318 }
319
320 /* ----------------------------------- */
321 static int new_ad_header(struct adouble *ad, const char *path, struct stat *stp, int adflags)
322 {
323     const struct entry  *eid;
324     uint16_t            ashort;
325     struct stat         st;
326
327     LOG(log_debug, logtype_default, "new_ad_header(\"%s\")", path);
328
329     if (stp == NULL) {
330         stp = &st;
331         if (lstat(path, &st) != 0)
332             return -1;
333     }
334
335     ad->ad_magic = AD_MAGIC;
336     ad->ad_version = ad->ad_vers & 0x0f0000;
337     if (!ad->ad_version) {
338         ad->ad_version = AD_VERSION;
339     }
340
341     memset(ad->ad_data, 0, sizeof(ad->ad_data));
342
343     if (ad->ad_vers == AD_VERSION2)
344         eid = entry_order2;
345     else if (ad->ad_vers == AD_VERSION_EA)
346         eid = entry_order_ea;
347     else if (ad->ad_vers == AD_VERSION2_OSX)
348         eid = entry_order_osx;
349     else {
350         return -1;
351     }
352
353     while (eid->id) {
354         ad->ad_eid[eid->id].ade_off = eid->offset;
355         ad->ad_eid[eid->id].ade_len = eid->len;
356         eid++;
357     }
358
359     /* put something sane in the directory finderinfo */
360     if (ad->ad_vers != AD_VERSION2_OSX) {
361         if ((adflags & ADFLAGS_DIR)) {
362             /* set default view */
363             ashort = htons(FINDERINFO_CLOSEDVIEW);
364             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
365         } else {
366             /* set default creator/type fields */
367             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
368             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
369         }
370
371         /* make things invisible */
372         if ((ad->ad_options & ADVOL_INVDOTS)
373             && (*path == '.')
374             && !((adflags & ADFLAGS_DIR) && (path[1] == 0))
375             ) {
376             ashort = htons(ATTRBIT_INVISIBLE);
377             ad_setattr(ad, ashort);
378             ashort = htons(FINDERINFO_INVISIBLE);
379             memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
380         }
381
382         /* put something sane in the date fields */
383         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, stp->st_mtime);
384         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, stp->st_mtime);
385         ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, stp->st_mtime);
386         ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
387     }
388     return 0;
389 }
390
391 /* -------------------------------------
392    read in the entries
393 */
394 static void parse_entries(struct adouble *ad, char *buf, uint16_t nentries)
395 {
396     uint32_t   eid, len, off;
397     int        warning = 0;
398
399     /* now, read in the entry bits */
400     for (; nentries > 0; nentries-- ) {
401         memcpy(&eid, buf, sizeof( eid ));
402         eid = get_eid(ntohl(eid));
403         buf += sizeof( eid );
404         memcpy(&off, buf, sizeof( off ));
405         off = ntohl( off );
406         buf += sizeof( off );
407         memcpy(&len, buf, sizeof( len ));
408         len = ntohl( len );
409         buf += sizeof( len );
410
411         if (eid
412             && eid < ADEID_MAX
413             && off < sizeof(ad->ad_data)
414             && (off + len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
415             ad->ad_eid[ eid ].ade_off = off;
416             ad->ad_eid[ eid ].ade_len = len;
417         } else if (!warning) {
418             warning = 1;
419             LOG(log_warning, logtype_default, "parse_entries: bogus eid: %d", eid);
420         }
421     }
422 }
423
424 /* this reads enough of the header so that we can figure out all of
425  * the entry lengths and offsets. once that's done, we just read/mmap
426  * the rest of the header in.
427  *
428  * NOTE: we're assuming that the resource fork is kept at the end of
429  *       the file. also, mmapping won't work for the hfs fs until it
430  *       understands how to mmap header files. */
431 static int ad_header_read(const char *path _U_, struct adouble *ad, struct stat *hst)
432 {
433     char                *buf = ad->ad_data;
434     uint16_t            nentries;
435     int                 len;
436     ssize_t             header_len;
437     struct stat         st;
438
439     /* read the header */
440     if ((header_len = adf_pread( ad->ad_mdp, buf, AD_DATASZ, 0)) < 0) {
441         return -1;
442     }
443     if (header_len < AD_HEADER_LEN) {
444         errno = EIO;
445         return -1;
446     }
447
448     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
449     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
450     ad->ad_magic = ntohl( ad->ad_magic );
451     ad->ad_version = ntohl( ad->ad_version );
452
453     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
454         LOG(log_error, logtype_default, "ad_open: can't parse AppleDouble header.");
455         errno = EIO;
456         return -1;
457     }
458
459     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
460     nentries = ntohs( nentries );
461
462     /* read in all the entry headers. if we have more than the
463      * maximum, just hope that the rfork is specified early on. */
464     len = nentries*AD_ENTRY_LEN;
465
466     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
467         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
468
469     buf += AD_HEADER_LEN;
470     if (len > header_len - AD_HEADER_LEN) {
471         LOG(log_error, logtype_default, "ad_header_read: can't read entry info.");
472         errno = EIO;
473         return -1;
474     }
475
476     /* figure out all of the entry offsets and lengths. if we aren't
477      * able to read a resource fork entry, bail. */
478     nentries = len / AD_ENTRY_LEN;
479     parse_entries(ad, buf, nentries);
480     if (!ad_getentryoff(ad, ADEID_RFORK)
481         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
482         ) {
483         LOG(log_error, logtype_default, "ad_header_read: problem with rfork entry offset.");
484         errno = EIO;
485         return -1;
486     }
487
488     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
489         LOG(log_error, logtype_default, "ad_header_read: can't read in entries.");
490         errno = EIO;
491         return -1;
492     }
493
494     if (hst == NULL) {
495         hst = &st;
496         if (fstat(ad->ad_mdp->adf_fd, &st) < 0) {
497             return 1; /* fail silently */
498         }
499     }
500
501     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
502
503     return 0;
504 }
505
506 /* Read an ._ file, only uses the resofork, finderinfo is taken from EA */
507 static int ad_header_read_osx(const char *path _U_, struct adouble *ad, struct stat *hst)
508 {
509     EC_INIT;
510     struct adouble      adosx;
511     char                *buf = &adosx.ad_data[0];
512     uint16_t            nentries;
513     int                 len;
514     ssize_t             header_len;
515     struct stat         st;
516
517     memset(buf, 0, sizeof(adosx.ad_data));
518
519     /* read the header */
520     EC_NEG1( header_len = adf_pread(ad->ad_rfp, buf, AD_DATASZ_OSX, 0) );
521
522     if (header_len < AD_HEADER_LEN) {
523         errno = EIO;
524         return -1;
525     }
526
527     memcpy(&adosx.ad_magic, buf, sizeof(adosx.ad_magic));
528     memcpy(&adosx.ad_version, buf + ADEDOFF_VERSION, sizeof(adosx.ad_version));
529     adosx.ad_magic = ntohl(adosx.ad_magic);
530     adosx.ad_version = ntohl(adosx.ad_version);
531
532     if ((adosx.ad_magic != AD_MAGIC) || (adosx.ad_version != AD_VERSION2)) {
533         LOG(log_error, logtype_afpd, "ad_header_read_osx: can't parse AppleDouble header");
534         errno = EIO;
535         return -1;
536     }
537
538     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
539     nentries = ntohs(nentries);
540     len = nentries * AD_ENTRY_LEN;
541
542     if (len + AD_HEADER_LEN > sizeof(adosx.ad_data))
543         len = sizeof(adosx.ad_data) - AD_HEADER_LEN;
544
545     buf += AD_HEADER_LEN;
546     if (len > header_len - AD_HEADER_LEN) {
547         LOG(log_error, logtype_afpd, "ad_header_read_osx: can't read entry info.");
548         errno = EIO;
549         return -1;
550     }
551
552     nentries = len / AD_ENTRY_LEN;
553     parse_entries(&adosx, buf, nentries);
554
555     if (ad_getentryoff(&adosx, ADEID_RFORK) == 0
556         || ad_getentryoff(&adosx, ADEID_RFORK) > sizeof(ad->ad_data)
557         || ad_getentryoff(&adosx, ADEID_RFORK) > header_len
558         ) {
559         LOG(log_error, logtype_afpd, "ad_header_read_osx: problem with rfork entry offset.");
560         errno = EIO;
561         return -1;
562     }
563
564     if (hst == NULL) {
565         hst = &st;
566         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
567     }
568
569     ad_setentryoff(ad, ADEID_RFORK, ad_getentryoff(&adosx, ADEID_RFORK));
570     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
571
572 EC_CLEANUP:
573     EC_EXIT;
574 }
575
576 static int ad_header_read_ea(const char *path, struct adouble *ad, struct stat *hst _U_)
577 {
578     uint16_t nentries;
579     int      len;
580     ssize_t  header_len;
581     char     *buf = ad->ad_data;
582
583     if (ad_meta_fileno(ad) != -1)
584         header_len = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_META, ad->ad_data, AD_DATASZ_EA);
585     else
586         header_len = sys_lgetxattr(path, AD_EA_META, ad->ad_data, AD_DATASZ_EA);
587      if (header_len < 1) {
588         LOG(log_debug, logtype_default, "ad_header_read_ea: %s", strerror(errno));
589         return -1;
590     }
591
592     if (header_len < AD_HEADER_LEN) {
593         LOG(log_error, logtype_default, "ad_header_read_ea: bogus AppleDouble header.");
594         errno = EIO;
595         return -1;
596     }
597
598     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
599     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
600
601     ad->ad_magic = ntohl( ad->ad_magic );
602     ad->ad_version = ntohl( ad->ad_version );
603
604     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
605         LOG(log_error, logtype_default, "ad_header_read_ea: wrong magic or version");
606         errno = EIO;
607         return -1;
608     }
609
610     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
611     nentries = ntohs( nentries );
612
613     /* Protect against bogus nentries */
614     len = nentries * AD_ENTRY_LEN;
615     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
616         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
617     if (len > header_len - AD_HEADER_LEN) {
618         LOG(log_error, logtype_default, "ad_header_read_ea: can't read entry info.");
619         errno = EIO;
620         return -1;
621     }
622     nentries = len / AD_ENTRY_LEN;
623
624     /* Now parse entries */
625     parse_entries(ad, buf + AD_HEADER_LEN, nentries);
626
627     return 0;
628 }
629
630 /*!
631  * Takes a path to an AppleDouble file and creates the parrent .AppleDouble directory
632  *
633  * Example:
634  * path: "/path/.AppleDouble/file"
635  * => mkdir("/path/.AppleDouble/") (in ad_mkdir())
636  */
637 static int ad_mkrf(const char *path)
638 {
639     char *slash;
640     /*
641      * Probably .AppleDouble doesn't exist, try to mkdir it.
642      */
643     if (NULL == ( slash = strrchr( path, '/' )) ) {
644         return -1;
645     }
646     *slash = '\0';
647     errno = 0;
648     if ( ad_mkdir( path, 0777 ) < 0 ) {
649         return -1;
650     }
651     *slash = '/';
652     return 0;
653 }
654
655 static int ad_mkrf_ea(const char *path _U_)
656 {
657     AFP_PANIC("ad_mkrf_ea: dont use");
658     return 0;
659 }
660
661 static int ad_mkrf_osx(const char *path _U_)
662 {
663     return 0;
664 }
665
666 /* ----------------
667    if we are root change path user/ group
668    It can be a native function for BSD cf. FAQ.Q10
669    path:  pathname to chown
670    stbuf: parent directory inode
671
672    use fstat and fchown or lchown with linux?
673 */
674 #define EMULATE_SUIDDIR
675
676 static int ad_chown(const char *path, struct stat *stbuf)
677 {
678     int ret = 0;
679 #ifdef EMULATE_SUIDDIR
680     uid_t id;
681
682     if (default_uid != (uid_t)-1) {
683         /* we are root (admin) */
684         id = (default_uid)?default_uid:stbuf->st_uid;
685         ret = lchown( path, id, stbuf->st_gid );
686     }
687 #endif
688     return ret;
689 }
690
691 #define DEFMASK 07700   /* be conservative */
692
693 /* ----------------
694    return access right and inode of path parent directory
695 */
696 static int ad_mode_st(const char *path, mode_t *mode, struct stat *stbuf)
697 {
698     if (*mode == 0) {
699         return -1;
700     }
701     if (ad_stat(path, stbuf) != 0) {
702         *mode &= DEFMASK;
703         return -1;
704     }
705     *mode &= stbuf->st_mode;
706     return 0;
707 }
708
709 /* --------------------------- */
710 static int ad_header_upgrade(struct adouble *ad _U_, const char *name _U_)
711 {
712     return 0;
713 }
714
715 static int ad_header_upgrade_ea(struct adouble *ad _U_, const char *name _U_)
716 {
717     AFP_PANIC("ad_header_upgrade_ea: dont use");
718     return 0;
719 }
720
721 /*!
722  * Error handling for adouble header(=metadata) file open error
723  *
724  * We're called because opening ADFLAGS_HF caused an error.
725  * 1. In case ad_open is called with ADFLAGS_NOHF the error is suppressed.
726  * 2. If ad_open was called with ADFLAGS_DF we may have opened the datafork and thus
727  *    ought to close it before returning with an error condition.
728  */
729 static int ad_error(struct adouble *ad, int adflags)
730 {
731     int err = errno;
732     if (adflags & ADFLAGS_NOHF) { /* 1 */
733         return 0;
734     }
735     if (adflags & (ADFLAGS_DF | ADFLAGS_SETSHRMD | ADFLAGS_CHECK_OF)) { /* 2 */
736         ad_close( ad, ADFLAGS_DF );
737         err = errno;
738     }
739     return -1 ;
740 }
741
742 /*!
743  * Map ADFLAGS to open() flags
744  *
745  * @param adfile   (r) the file you really want to open: ADFLAGS_DF or ADFLAGS_HF
746  * @param adflags  (r) flags from ad_open(..., adflags, ...)
747  * @returns            mapped flags suitable for calling open()
748  */
749 static int ad2openflags(const struct adouble *ad, int adfile, int adflags)
750 {
751     int oflags = 0;
752
753     if (adflags & ADFLAGS_RDWR)
754         oflags |= O_RDWR;
755     if (adflags & ADFLAGS_RDONLY) {
756         if (((adfile == ADFLAGS_DF || adfile == ADFLAGS_RF) && (adflags & ADFLAGS_SETSHRMD))
757             /* need rw access for locks */
758             || ((adfile == ADFLAGS_HF) && (ad->ad_vers == AD_VERSION2)))
759             /* need rw access for adouble file for the case:
760              1) openfork(data+meta:O_RDONLY), 2) openfork(reso(=meta):O_RDWR) */
761             oflags |= O_RDWR;
762         else
763             oflags |= O_RDONLY;
764     }
765     if (adflags & ADFLAGS_CREATE)
766         oflags |= O_CREAT;
767     if (adflags & ADFLAGS_EXCL)
768         oflags |= O_EXCL;
769     if (adflags & ADFLAGS_TRUNC)
770         oflags |= O_TRUNC;
771
772     return oflags;
773 }
774
775 static int ad_open_df(const char *path, int adflags, mode_t mode, struct adouble *ad)
776 {
777     EC_INIT;
778     struct stat st_dir;
779     int         oflags;
780     mode_t      admode;
781     int         st_invalid = -1;
782     ssize_t     lsz;
783
784     LOG(log_debug, logtype_default,
785         "ad_open_df(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
786         fullpathname(path), adflags2logstr(adflags),
787         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
788         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
789         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
790
791     if (ad_data_fileno(ad) != -1) {
792         /* the file is already open, but we want write access: */
793         if ((adflags & ADFLAGS_RDWR)
794             /* and it was denied the first time: */
795             && (ad->ad_data_fork.adf_flags & O_RDONLY)) {
796                 errno = EACCES;
797                 return -1;
798             }
799         /* it's not new anymore */
800         ad->ad_data_fork.adf_flags &= ~( O_TRUNC | O_CREAT );
801         ad->ad_data_fork.adf_refcount++;
802         goto EC_CLEANUP;
803     }
804
805     oflags = O_NOFOLLOW | ad2openflags(ad, ADFLAGS_DF, adflags);
806
807     admode = mode;
808     if ((adflags & ADFLAGS_CREATE)) {
809         st_invalid = ad_mode_st(path, &admode, &st_dir);
810         if ((ad->ad_options & ADVOL_UNIXPRIV))
811             admode = mode;
812     }
813
814     ad->ad_data_fork.adf_fd = open(path, oflags, admode);
815
816     if (ad->ad_data_fork.adf_fd == -1) {
817         switch (errno) {
818         case EACCES:
819         case EPERM:
820         case EROFS:
821             if ((adflags & ADFLAGS_SETSHRMD) && (adflags & ADFLAGS_RDONLY)) {
822                 oflags &= ~O_RDWR;
823                 oflags |= O_RDONLY;
824                 EC_NEG1( ad->ad_data_fork.adf_fd = open(path, oflags, admode) );
825                 break;
826             }
827             return -1;
828         case OPEN_NOFOLLOW_ERRNO:
829             ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
830             if ((lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN)) <= 0) {
831                 free(ad->ad_data_fork.adf_syml);
832                 EC_FAIL;
833             }
834             ad->ad_data_fork.adf_syml[lsz] = 0;
835             ad->ad_data_fork.adf_fd = -2; /* -2 means its a symlink */
836             break;
837         default:
838             EC_FAIL;
839         }
840     }
841
842     if (!st_invalid)
843         ad_chown(path, &st_dir); /* just created, set owner if admin (root) */
844
845     ad->ad_data_fork.adf_flags = oflags;
846     adf_lock_init(&ad->ad_data_fork);
847     ad->ad_data_fork.adf_refcount++;
848
849 EC_CLEANUP:
850     LOG(log_debug, logtype_default,
851         "ad_open_df(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
852         fullpathname(path), adflags2logstr(adflags), ret,
853         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
854         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
855         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
856     EC_EXIT;
857 }
858
859 static int ad_open_hf_v2(const char *path, int adflags, mode_t mode, struct adouble *ad)
860 {
861     EC_INIT;
862     struct stat st_dir;
863     struct stat st_meta;
864     struct stat *pst = NULL;
865     const char  *ad_p;
866     int         oflags, nocreatflags, opened = 0;
867     mode_t      admode;
868     int         st_invalid = -1;
869
870     LOG(log_debug, logtype_default,
871         "ad_open_hf_v2(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
872         fullpathname(path), adflags2logstr(adflags),
873         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
874         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
875         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
876
877     if (ad_meta_fileno(ad) != -1) {
878         /* the file is already open, but we want write access: */
879         if ((adflags & ADFLAGS_RDWR) &&
880             /* and it was already denied: */
881             (ad->ad_mdp->adf_flags & O_RDONLY)) {
882             errno = EACCES;
883             EC_FAIL;
884         }
885         ad_refresh(path, ad);
886         /* it's not new anymore */
887         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
888         ad->ad_mdp->adf_refcount++;
889         goto EC_CLEANUP;
890     }
891
892     ad_p = ad->ad_ops->ad_path(path, adflags);
893     oflags = O_NOFOLLOW | ad2openflags(ad, ADFLAGS_HF, adflags);
894     LOG(log_debug, logtype_default,"ad_open_hf_v2(\"%s\"): open flags: %s",
895         fullpathname(path), openflags2logstr(oflags));
896     nocreatflags = oflags & ~(O_CREAT | O_EXCL);
897
898     ad_meta_fileno(ad) = open(ad_p, nocreatflags);
899
900     if (ad_meta_fileno(ad) != -1) {
901         ad->ad_mdp->adf_flags = nocreatflags;
902     } else {
903         switch (errno) {
904         case EACCES:
905         case EPERM:
906         case EROFS:
907             if ((adflags & ADFLAGS_RDONLY) && (adflags & ADFLAGS_SETSHRMD)) {
908                 nocreatflags &= ~O_RDWR;
909                 nocreatflags |= O_RDONLY;
910                 EC_NEG1( ad_meta_fileno(ad) = open(ad_p, nocreatflags) );
911                 ad->ad_mdp->adf_flags = nocreatflags;
912                 break;
913             }
914             EC_FAIL;
915         case ENOENT:
916             if (!(oflags & O_CREAT))
917                 EC_FAIL;
918             /*
919              * We're expecting to create a new adouble header file here
920              */
921             LOG(log_debug, logtype_default, "ad_open(\"%s\"): creating adouble file",
922                 fullpathname(path));
923             admode = mode;
924             errno = 0;
925             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
926             if ((ad->ad_options & ADVOL_UNIXPRIV))
927                 admode = mode;
928             admode = ad_hf_mode(admode);
929             if (errno == ENOENT) {
930                 EC_NEG1_LOG( ad->ad_ops->ad_mkrf(ad_p) );
931                 admode = mode;
932                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
933                 if ((ad->ad_options & ADVOL_UNIXPRIV))
934                     admode = mode;
935                 admode = ad_hf_mode(admode);
936             }
937
938             /* retry with O_CREAT */
939             EC_NEG1( ad_meta_fileno(ad) = open(ad_p, oflags, admode) );
940             ad->ad_mdp->adf_flags = oflags;
941             /* just created, set owner if admin owner (root) */
942             if (!st_invalid)
943                 ad_chown(ad_p, &st_dir);
944             break;
945         default:
946             EC_FAIL;
947         }
948     }
949
950     /* Now we've got a new opened fd, we need to check that in the error case */
951     opened = 1;
952
953     if (!(ad->ad_mdp->adf_flags & O_CREAT)) {
954         /* check for 0 length files, treat them as new. */
955         if (fstat(ad->ad_mdp->adf_fd, &st_meta) == 0) {
956             if (st_meta.st_size == 0)
957                 ad->ad_mdp->adf_flags |= O_TRUNC;
958             else
959                 /* we have valid data in st_meta stat structure, reused it in ad_header_read */
960                 pst = &st_meta;
961         }
962     }
963
964     adf_lock_init(ad->ad_mdp);
965     ad->ad_mdp->adf_refcount = 1;
966
967     if ((ad->ad_mdp->adf_flags & ( O_TRUNC | O_CREAT ))) {
968         /* This is a new adouble header file, create it */
969         EC_NEG1_LOG( new_ad_header(ad, path, pst, adflags) );
970         ad_flush(ad);
971     } else {
972         /* Read the adouble header in and parse it.*/
973         EC_NEG1_LOG( ad->ad_ops->ad_header_read(path, ad, pst) );
974     }
975
976 EC_CLEANUP:
977     if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
978         close(ad_meta_fileno(ad));
979         ad_meta_fileno(ad) = -1;
980         ad->ad_mdp->adf_refcount = 0;
981     }
982     LOG(log_debug, logtype_default,
983         "ad_open_hf_v2(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
984         fullpathname(path), adflags2logstr(adflags), ret,
985         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
986         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
987         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
988     EC_EXIT;
989 }
990
991 static int ad_open_hf_ea(const char *path, int adflags, int mode, struct adouble *ad)
992 {
993     EC_INIT;
994     ssize_t rforklen;
995     int oflags;
996     int opened = 0;
997
998     LOG(log_debug, logtype_default,
999         "ad_open_hf_ea(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1000         fullpathname(path), adflags2logstr(adflags),
1001         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1002         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1003         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1004
1005     oflags = O_NOFOLLOW | (ad2openflags(ad, ADFLAGS_DF, adflags) & ~(O_CREAT | O_TRUNC));
1006
1007     if (ad_meta_fileno(ad) == -2)
1008         /* symlink */
1009         EC_EXIT;
1010
1011     if (ad_meta_fileno(ad) != -1) {
1012         /* the file is already open, but we want write access: */
1013         if ((oflags & O_RDWR) &&
1014             /* and it was already denied: */
1015             (ad->ad_mdp->adf_flags & O_RDONLY)) {
1016             LOG(log_error, logtype_default, "ad_open_hf_ea(%s): rw request for ro file: %s",
1017                 fullpathname(path), strerror(errno));
1018             errno = EACCES;
1019             EC_FAIL;
1020         }
1021         /* it's not new anymore */
1022         ad->ad_mdp->adf_flags &= ~( O_TRUNC | O_CREAT );
1023     } else {
1024         if (oflags & O_RDWR) {
1025             /* Fo a RDONLY adouble we just use sys_lgetxattr instead if sys_fgetxattr */
1026             if (adflags & ADFLAGS_DIR)
1027                 /* For directories we open the directory RDONYL so we can later fchdir()  */
1028                 oflags = (oflags & ~O_RDWR) | O_RDONLY;
1029             LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): opening base file for meta adouble EA", path);
1030             EC_NEG1(ad_meta_fileno(ad) = open(path, oflags));
1031             opened = 1;
1032             ad->ad_mdp->adf_flags = oflags;
1033         }
1034     }
1035
1036     /* Read the adouble header in and parse it.*/
1037     if (ad->ad_ops->ad_header_read(path, ad, NULL) != 0) {
1038         if (!(adflags & ADFLAGS_CREATE)) {
1039             LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): can't read metadata EA", path);
1040             errno = ENOENT;
1041             EC_FAIL;
1042         }
1043
1044         LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): creating metadata EA", path);
1045
1046         /* It doesnt exist, EPERM or another error */
1047         if (!(errno == ENOATTR || errno == ENOENT)) {
1048             LOG(log_error, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
1049             EC_FAIL;
1050         }
1051
1052         /* Create one */
1053         EC_NEG1_LOG(new_ad_header(ad, path, NULL, adflags));
1054         ad->ad_mdp->adf_flags |= O_CREAT; /* mark as just created */
1055         ad_flush(ad);
1056         LOG(log_debug, logtype_default, "ad_open_hf_ea(\"%s\"): created metadata EA", path);
1057     }
1058
1059     ad->ad_mdp->adf_refcount++;
1060     (void)ad_reso_size(path, adflags, ad);
1061
1062 EC_CLEANUP:
1063     if (ret != 0 && opened && ad_meta_fileno(ad) != -1) {
1064         close(ad_meta_fileno(ad));
1065         ad_meta_fileno(ad) = -1;
1066         ad->ad_mdp->adf_refcount = 0;
1067     }
1068     LOG(log_debug, logtype_default,
1069         "ad_open_hf_ea(\"%s\", %s): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1070         fullpathname(path), adflags2logstr(adflags), ret,
1071         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1072         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1073         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1074         
1075     EC_EXIT;
1076 }
1077
1078 static int ad_open_hf(const char *path, int adflags, int mode, struct adouble *ad)
1079 {
1080     int ret = 0;
1081
1082     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
1083     ad->ad_rlen = 0;
1084
1085     switch (ad->ad_vers) {
1086     case AD_VERSION2:
1087         ret = ad_open_hf_v2(path, adflags, mode, ad);
1088         break;
1089     case AD_VERSION_EA:
1090         ret = ad_open_hf_ea(path, adflags, mode, ad);
1091         break;
1092     default:
1093         ret = -1;
1094         break;
1095     }
1096
1097     if (ret != 0)
1098         ret = ad_error(ad, adflags);
1099
1100     return ret;
1101 }
1102
1103 /*!
1104  * Get resofork length for adouble:ea
1105  */
1106 static int ad_reso_size(const char *path, int adflags, struct adouble *ad)
1107 {
1108     EC_INIT;
1109     struct stat st;
1110
1111     LOG(log_debug, logtype_default, "ad_reso_size(\"%s\")", path);
1112
1113 #ifdef HAVE_EAFD
1114     ssize_t easz;
1115
1116     if (ad_reso_fileno(ad) != -1) {
1117         EC_NEG1( fstat(ad_reso_fileno(ad), &st) );
1118         ad->ad_rlen = st.st_size;
1119     } else if (ad_meta_fileno(ad) != -1) {
1120         EC_NEG1( easz = sys_fgetxattr(ad_meta_fileno(ad), AD_EA_RESO, NULL, 0) );
1121         ad->ad_rlen = easz;
1122     } else {
1123         EC_FAIL;
1124     }
1125
1126 #else
1127     const char *rfpath;
1128     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags));
1129     EC_ZERO( lstat(rfpath, &st));
1130     if (st.st_size > ADEDOFF_RFORK_OSX)
1131         ad->ad_rlen = st.st_size - ADEDOFF_RFORK_OSX;
1132     else
1133         ad->ad_rlen = 0;
1134 #endif
1135
1136     LOG(log_debug, logtype_default, "ad_reso_size(\"%s\"): size: %zd", path, ad->ad_rlen);
1137
1138 EC_CLEANUP:
1139     if (ret != 0)
1140         ad->ad_rlen = 0;
1141     EC_EXIT;
1142 }
1143
1144 /*!
1145  * Open ressource fork
1146  *
1147  * Only for adouble:ea, a nullop otherwise because adouble:v2 has the ressource fork as part
1148  * of the adouble file which is openend by ADFLAGS_HF.
1149  */
1150 static int ad_open_rf(const char *path, int adflags, int mode, struct adouble *ad)
1151 {
1152     EC_INIT;
1153     int oflags;
1154     int opened = 0;
1155     int closeflags = adflags & (ADFLAGS_DF | ADFLAGS_HF);
1156     ssize_t rlen;
1157 #ifndef HAVE_EAFD
1158     const char *rfpath;
1159     struct stat st;
1160 #endif
1161
1162     if (ad->ad_vers != AD_VERSION_EA)
1163         return 0;
1164
1165     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): BEGIN", fullpathname(path));
1166
1167     oflags = O_NOFOLLOW | (ad2openflags(ad, ADFLAGS_RF, adflags) & ~O_CREAT);
1168
1169     if (ad_reso_fileno(ad) != -1) {
1170         /* the file is already open, but we want write access: */
1171         if ((oflags & O_RDWR)
1172             /* and it was already denied: */
1173             && (ad->ad_rfp->adf_flags & O_RDONLY)) {
1174             errno = EACCES;
1175             EC_FAIL;
1176         }
1177         ad->ad_rfp->adf_flags &= ~( O_TRUNC | O_CREAT );
1178         ad->ad_rfp->adf_refcount++;
1179         EC_NEG1_LOG( ad_reso_size(path, adflags, ad));
1180         goto EC_CLEANUP;
1181     }
1182 #ifdef HAVE_EAFD
1183     if (ad_meta_fileno(ad) == -1)
1184         EC_FAIL;
1185     if ((ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad), AD_EA_RESO, oflags)) == -1) {
1186         if (!(adflags & ADFLAGS_CREATE)) {
1187             errno = ENOENT;
1188             EC_FAIL;
1189         }
1190         oflags |= O_CREAT;
1191         EC_NEG1_LOG( ad_reso_fileno(ad) = sys_getxattrfd(ad_meta_fileno(ad),
1192                                                          AD_EA_RESO, oflags, 0666) ); 
1193     }
1194 #else
1195     EC_NULL_LOG( rfpath = ad->ad_ops->ad_path(path, adflags) );
1196     if ((ad_reso_fileno(ad) = open(rfpath, oflags)) == -1) {
1197         if (!(adflags & ADFLAGS_CREATE))
1198             EC_FAIL;
1199         oflags |= O_CREAT;
1200         EC_NEG1_LOG( ad_reso_fileno(ad) = open(rfpath, oflags, mode) );
1201         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork: \"%s\"",
1202             path, rfpath);
1203     }
1204 #endif
1205     opened = 1;
1206     ad->ad_rfp->adf_refcount = 1;
1207     ad->ad_rfp->adf_flags = oflags;
1208
1209 #ifndef HAVE_EAFD
1210     EC_ZERO_LOG( fstat(ad_reso_fileno(ad), &st) );
1211     if (ad->ad_rfp->adf_flags & O_CREAT) {
1212         /* This is a new adouble header file, create it */
1213         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, initializing: \"%s\"",
1214             path, rfpath);
1215         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): created adouble rfork, flushing: \"%s\"",
1216             path, rfpath);
1217         ad_flush(ad);
1218     } else {
1219         /* Read the adouble header */
1220         LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): reading adouble rfork: \"%s\"",
1221             path, rfpath);
1222         EC_NEG1_LOG( ad_header_read_osx(NULL, ad, &st) );
1223     }
1224 #endif
1225
1226     (void)ad_reso_size(path, adflags, ad);
1227
1228 EC_CLEANUP:
1229     if (ret != 0) {
1230         if (opened && (ad_reso_fileno(ad) != -1)) {
1231             close(ad_reso_fileno(ad));
1232             ad_reso_fileno(ad) = -1;
1233             ad->ad_rfp->adf_refcount = 0;
1234         }
1235         if (adflags & ADFLAGS_NORF) {
1236             ret = 0;
1237         } else {
1238             int err = errno;
1239             (void)ad_close(ad, closeflags);
1240             errno = err;
1241         }
1242         ad->ad_rlen = 0;
1243     }
1244
1245     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\"): END: %d", fullpathname(path), ret);
1246
1247     EC_EXIT;
1248 }
1249
1250 /***********************************************************************************
1251  * API functions
1252  ********************************************************************************* */
1253
1254 off_t ad_getentryoff(const struct adouble *ad, int eid)
1255 {
1256     if (ad->ad_vers == AD_VERSION2)
1257         return ad->ad_eid[eid].ade_off;
1258
1259     switch (eid) {
1260     case ADEID_DFORK:
1261         return 0;
1262     case ADEID_RFORK:
1263 #ifdef HAVE_EAFD
1264         return 0;
1265 #else
1266         return ADEDOFF_RFORK_OSX;
1267 #endif
1268     default:
1269         return ad->ad_eid[eid].ade_off;
1270     }
1271     /* deadc0de */
1272     AFP_PANIC("What am I doing here?");
1273 }
1274
1275 const char *ad_path_ea( const char *path, int adflags _U_)
1276 {
1277     return path;
1278 }
1279
1280 const char *ad_path_osx(const char *path, int adflags _U_)
1281 {
1282     static char pathbuf[ MAXPATHLEN + 1];
1283     char    c, *slash, buf[MAXPATHLEN + 1];
1284
1285     if (!strcmp(path,".")) {
1286         /* fixme */
1287         getcwd(buf, MAXPATHLEN);
1288     }
1289     else {
1290         strlcpy(buf, path, MAXPATHLEN +1);
1291     }
1292     if (NULL != ( slash = strrchr( buf, '/' )) ) {
1293         c = *++slash;
1294         *slash = '\0';
1295         strlcpy( pathbuf, buf, MAXPATHLEN +1);
1296         *slash = c;
1297     } else {
1298         pathbuf[ 0 ] = '\0';
1299         slash = buf;
1300     }
1301     strlcat( pathbuf, "._", MAXPATHLEN  +1);
1302     strlcat( pathbuf, slash, MAXPATHLEN +1);
1303     return pathbuf;
1304 }
1305
1306 /*
1307  * Put the .AppleDouble where it needs to be:
1308  *
1309  *      /   a/.AppleDouble/b
1310  *  a/b
1311  *      \   b/.AppleDouble/.Parent
1312  *
1313  * FIXME: should do something for pathname > MAXPATHLEN
1314  */
1315 const char *ad_path( const char *path, int adflags)
1316 {
1317     static char pathbuf[ MAXPATHLEN + 1];
1318     const char *slash;
1319     size_t  l ;
1320
1321     if ( adflags & ADFLAGS_DIR ) {
1322         l = strlcpy( pathbuf, path, sizeof(pathbuf));
1323
1324         if ( l && l < MAXPATHLEN) {
1325             pathbuf[l++] = '/';
1326         }
1327         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
1328     } else {
1329         if (NULL != ( slash = strrchr( path, '/' )) ) {
1330             slash++;
1331             l = slash - path;
1332             /* XXX we must return NULL here and test in the caller */
1333             if (l > MAXPATHLEN)
1334                 l = MAXPATHLEN;
1335             memcpy( pathbuf, path, l);
1336         } else {
1337             l = 0;
1338             slash = path;
1339         }
1340         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
1341         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
1342     }
1343
1344     return( pathbuf );
1345 }
1346
1347 /* -------------------------
1348  * Support inherited protection modes for AppleDouble files.  The supplied
1349  * mode is ANDed with the parent directory's mask value in lieu of "umask",
1350  * and that value is returned.
1351  */
1352 char *ad_dir(const char *path)
1353 {
1354     static char     modebuf[ MAXPATHLEN + 1];
1355     char        *slash;
1356     /*
1357      * For a path with directories in it, remove the final component
1358      * (path or subdirectory name) to get the name we want to stat.
1359      * For a path which is just a filename, use "." instead.
1360      */
1361     slash = strrchr( path, '/' );
1362     if (slash) {
1363         size_t len;
1364
1365         len = slash - path;
1366         if (len >= MAXPATHLEN) {
1367             errno = ENAMETOOLONG;
1368             return NULL;  /* can't do it */
1369         }
1370         memcpy( modebuf, path, len );
1371         modebuf[len] = '\0';
1372         /* is last char a '/' ? */
1373         if (slash[1] == 0) {
1374             slash = modebuf+ len;
1375             /* remove them */
1376             while (modebuf < slash && slash[-1] == '/') {
1377                 --slash;
1378             }
1379             if (modebuf == slash) {
1380                 goto use_cur;
1381             }
1382             *slash = '\0';
1383             while (modebuf < slash && *slash != '/') {
1384                 --slash;
1385             }
1386             if (modebuf == slash) {
1387                 goto use_cur;
1388             }
1389             *slash = '\0';      /* remove pathname component */
1390         }
1391         return modebuf;
1392     }
1393 use_cur:
1394     modebuf[0] = '.';   /* use current directory */
1395     modebuf[1] = '\0';
1396     return modebuf;
1397 }
1398
1399 int ad_setfuid(const uid_t id)
1400 {
1401     default_uid = id;
1402     return 0;
1403 }
1404
1405 /* ---------------- */
1406 uid_t ad_getfuid(void)
1407 {
1408     return default_uid;
1409 }
1410
1411 /* ----------------
1412    stat path parent directory
1413 */
1414 int ad_stat(const char *path, struct stat *stbuf)
1415 {
1416     char *p;
1417
1418     p = ad_dir(path);
1419     if (!p)
1420         return -1;
1421     return lstat( p, stbuf );
1422 }
1423
1424 /* ----------------
1425    return access right of path parent directory
1426 */
1427 int ad_mode( const char *path, mode_t mode)
1428 {
1429     struct stat     stbuf;
1430     ad_mode_st(path, &mode, &stbuf);
1431     return mode;
1432 }
1433
1434 /*
1435  * Use mkdir() with mode bits taken from ad_mode().
1436  */
1437 int ad_mkdir( const char *path, mode_t mode)
1438 {
1439     int ret;
1440     int st_invalid;
1441     struct stat stbuf;
1442
1443     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
1444         path, mode, getcwdpath());
1445
1446     st_invalid = ad_mode_st(path, &mode, &stbuf);
1447     ret = mkdir( path, mode );
1448     if (ret || st_invalid)
1449         return ret;
1450     ad_chown(path, &stbuf);
1451
1452     return ret;
1453 }
1454
1455 static void ad_init_func(struct adouble *ad)
1456 {
1457     switch (ad->ad_vers) {
1458     case AD_VERSION2:
1459         ad->ad_ops = &ad_adouble;
1460         ad->ad_rfp = &ad->ad_resource_fork;
1461         ad->ad_mdp = &ad->ad_resource_fork;
1462         break;
1463     case AD_VERSION_EA:
1464         ad->ad_ops = &ad_adouble_ea;
1465         ad->ad_rfp = &ad->ad_resource_fork;
1466         ad->ad_mdp = &ad->ad_data_fork;
1467         break;
1468     default:
1469         AFP_PANIC("ad_init: unknown AD version");
1470     }
1471
1472
1473     ad_data_fileno(ad) = -1;
1474     ad_reso_fileno(ad) = -1;
1475     ad_meta_fileno(ad) = -1;
1476     ad->ad_refcount = 1;
1477     return;
1478 }
1479
1480 void ad_init_old(struct adouble *ad, int flags, int options)
1481 {
1482     memset(ad, 0, sizeof(struct adouble));
1483     ad->ad_vers = flags;
1484     ad->ad_options = options;
1485     ad_init_func(ad);
1486 }
1487
1488 void ad_init(struct adouble *ad, const struct vol * restrict vol)
1489 {
1490     memset(ad, 0, sizeof(struct adouble));
1491     ad->ad_vers = vol->v_adouble;
1492     ad->ad_options = vol->v_ad_options;
1493     ad_init_func(ad);
1494 }
1495
1496 /*!
1497  * Open data-, metadata(header)- or ressource fork
1498  *
1499  * ad_open(struct adouble *ad, const char *path, int adflags, int flags)
1500  * ad_open(struct adouble *ad, const char *path, int adflags, int flags, mode_t mode)
1501  *
1502  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1503  * @code
1504  *      struct adoube ad;
1505  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1506  * @endcode
1507  *
1508  * Open a files data fork, metadata fork or ressource fork.
1509  *
1510  * @param ad        (rw) pointer to struct adouble
1511  * @param path      (r)  Path to file or directory
1512  * @param adflags   (r)  Flags specifying which fork to open, can be or'd:
1513  *                         ADFLAGS_DF:        open data fork
1514  *                         ADFLAGS_RF:        open ressource fork
1515  *                         ADFLAGS_HF:        open header (metadata) file
1516  *                         ADFLAGS_NOHF:      it's not an error if header file couldn't be opened
1517  *                         ADFLAGS_NORF:      it's not an error if reso fork couldn't be opened
1518  *                         ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags
1519  *
1520  *                       Access mode for the forks:
1521  *                         ADFLAGS_RDONLY:    open read only
1522  *                         ADFLAGS_RDWR:      open read write
1523  *
1524  *                       Creation flags:
1525  *                         ADFLAGS_CREATE:    create if not existing
1526  *                         ADFLAGS_TRUNC:     truncate
1527  *
1528  *                       Special flags:
1529  *                         ADFLAGS_CHECK_OF:  check for open forks from us and other afpd's
1530  *                         ADFLAGS_SETSHRMD:  this adouble struct will be used to set sharemode locks.
1531  *                                            This basically results in the files being opened RW instead of RDONLY.
1532  * @param mode      (r)  mode used with O_CREATE
1533  *
1534  * The open mode flags (rw vs ro) have to take into account all the following requirements:
1535  * - we remember open fds for files because me must avoid a single close releasing fcntl locks for other
1536  *   fds of the same file
1537  *
1538  * @returns 0 on success, any other value indicates an error
1539  */
1540 int ad_open(struct adouble *ad, const char *path, int adflags, ...)
1541 {
1542     EC_INIT;
1543     va_list args;
1544     mode_t mode = 0;
1545
1546     LOG(log_debug, logtype_default,
1547         "ad_open(\"%s\", %s): BEGIN [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1548         fullpathname(path), adflags2logstr(adflags),
1549         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1550         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1551         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1552
1553     if (adflags & ADFLAGS_CHECK_OF)
1554         /* Checking for open forks requires sharemode lock support (ie RDWR instead of RDONLY) */
1555         adflags |= ADFLAGS_SETSHRMD;
1556
1557     if (ad->ad_vers == AD_VERSION2) {
1558         if (adflags & ADFLAGS_SETSHRMD)
1559             /* sharemode locks are stored in the data fork, adouble:v2 needs this extra handling here */
1560             adflags |= ADFLAGS_DF;
1561         if (adflags & ADFLAGS_RF)
1562             adflags |= ADFLAGS_HF;
1563         if (adflags & ADFLAGS_NORF)
1564             adflags |= ADFLAGS_NOHF;
1565     }
1566
1567     if (ad->ad_inited != AD_INITED) {
1568         ad->ad_adflags = adflags;
1569         ad->ad_inited = AD_INITED;
1570     } else {
1571         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1572         if (ad->ad_resource_fork.adf_refcount > 0)
1573             ad->ad_open_forks |= ATTRBIT_ROPEN;
1574     }
1575
1576     va_start(args, adflags);
1577     if (adflags & ADFLAGS_CREATE)
1578         mode = va_arg(args, mode_t);
1579     va_end(args);
1580
1581     if (adflags & ADFLAGS_DF) {
1582         EC_ZERO( ad_open_df(path, adflags, mode, ad) );
1583     }
1584
1585     if (adflags & ADFLAGS_HF) {
1586         EC_ZERO( ad_open_hf(path, adflags, mode, ad) );
1587     }
1588
1589     if (adflags & ADFLAGS_RF) {
1590         EC_ZERO( ad_open_rf(path, adflags, mode, ad) );
1591     }
1592
1593     if (adflags & ADFLAGS_CHECK_OF) {
1594         ad->ad_open_forks |= ad_openforks(ad, ad->ad_open_forks);
1595     }
1596
1597 EC_CLEANUP:
1598     LOG(log_debug, logtype_default,
1599         "ad_open(\"%s\"): END: %d [dfd: %d (ref: %d), mfd: %d (ref: %d), rfd: %d (ref: %d)]",
1600         fullpathname(path), ret,
1601         ad_data_fileno(ad), ad->ad_data_fork.adf_refcount,
1602         ad_meta_fileno(ad), ad->ad_mdp->adf_refcount,
1603         ad_reso_fileno(ad), ad->ad_rfp->adf_refcount);
1604
1605     EC_EXIT;
1606 }
1607
1608 /*!
1609  * @brief open metadata, possibly as root
1610  *
1611  * Return only metadata but try very hard ie at first try as user, then try as root.
1612  *
1613  * @param name  name of file/dir
1614  * @param flags ADFLAGS_DIR: name is a directory \n
1615  *              ADFLAGS_CHECK_OF: test if name is open by us or another afpd process
1616  *
1617  * @param adp   pointer to struct adouble
1618  */
1619 int ad_metadata(const char *name, int flags, struct adouble *adp)
1620 {
1621     uid_t uid;
1622     int   ret, err, oflags;
1623
1624     /* Sanitize flags */
1625     oflags = (flags & (ADFLAGS_CHECK_OF | ADFLAGS_DIR)) | ADFLAGS_HF | ADFLAGS_RDONLY;    
1626
1627     if ((ret = ad_open(adp, name, oflags)) < 0 && errno == EACCES) {
1628         uid = geteuid();
1629         if (seteuid(0)) {
1630             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1631             errno = EACCES;
1632             return -1;
1633         }
1634         /* we are root open read only */
1635         ret = ad_open(adp, name, oflags);
1636         err = errno;
1637         if ( seteuid(uid) < 0) {
1638             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1639             exit(EXITERR_SYS);
1640         }
1641         errno = err;
1642     }
1643
1644     return ret;
1645 }
1646
1647 /*
1648  * @brief openat like wrapper for ad_metadata
1649  */
1650 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1651 {
1652     int ret = 0;
1653     int cwdfd = -1;
1654
1655     if (dirfd != -1) {
1656         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1657             ret = -1;
1658             goto exit;
1659         }
1660     }
1661
1662     if (ad_metadata(name, flags, adp) < 0) {
1663         ret = -1;
1664         goto exit;
1665     }
1666
1667     if (dirfd != -1) {
1668
1669         if (fchdir(cwdfd) != 0) {
1670             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1671             exit(EXITERR_SYS);
1672         }
1673     }
1674
1675 exit:
1676     if (cwdfd != -1)
1677         close(cwdfd);
1678
1679     return ret;
1680
1681 }
1682
1683 int ad_refresh(const char *path, struct adouble *ad)
1684 {
1685     switch (ad->ad_vers) {
1686     case AD_VERSION2:
1687         if (ad_meta_fileno(ad) == -1)
1688             return -1;
1689         return ad->ad_ops->ad_header_read(NULL, ad, NULL);
1690         break;
1691     case AD_VERSION_EA:
1692 #ifdef HAVE_EAFD
1693         if (AD_META_OPEN(ad)) {
1694             if (ad_data_fileno(ad) == -1)
1695                 return -1;
1696             // TODO: read meta EA
1697         }
1698
1699         if (AD_RSRC_OPEN(ad)) {
1700             if (ad_reso_fileno(ad) == -1)
1701                 return -1;
1702             struct stat st;
1703             if (fstat(ad_reso_fileno(ad), &st) == -1)
1704                 return -1;
1705             ad->ad_rlen = st.st_size;
1706         }
1707 #else
1708         if (AD_META_OPEN(ad)) {
1709             if (ad_data_fileno(ad) == -1)
1710                 return -1;
1711             // TODO: read meta EA
1712         }
1713         if (AD_RSRC_OPEN(ad)) {
1714             if (ad_reso_fileno(ad) == -1)
1715                 return -1;
1716             if (ad_header_read_osx(path, ad, NULL) < 0)
1717                 return -1;
1718         }
1719 #endif
1720         return ad->ad_ops->ad_header_read(path, ad, NULL);
1721         break;
1722     default:
1723         return -1;
1724         break;
1725     }
1726
1727 }
1728
1729 int ad_openat(struct adouble  *ad,
1730               int dirfd,  /* dir fd openat like */
1731               const char *path,
1732               int adflags, ...)
1733 {
1734     EC_INIT;
1735     int cwdfd = -1;
1736     va_list args;
1737     mode_t mode;
1738
1739     if (dirfd != -1) {
1740         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0))
1741             EC_FAIL;
1742     }
1743
1744     va_start(args, adflags);
1745     if (adflags & ADFLAGS_CREATE)
1746         mode = va_arg(args, mode_t);
1747     va_end(args);
1748
1749     EC_NEG1( ad_open(ad, path, adflags, mode) );
1750
1751     if (dirfd != -1) {
1752         if (fchdir(cwdfd) != 0) {
1753             AFP_PANIC("ad_openat: cant chdir back");
1754         }
1755     }
1756
1757 EC_CLEANUP:
1758     if (cwdfd != -1)
1759         close(cwdfd);
1760
1761     return ret;
1762 }