]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Start of rfork EA stuff
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu)
3  * Copyright (c) 1990,1991 Regents of The University of Michigan.
4  * Copyright (c) 2010 Frank Lahm
5  *
6  * All Rights Reserved.
7  *
8  * Permission to use, copy, modify, and distribute this software and
9  * its documentation for any purpose and without fee is hereby granted,
10  * provided that the above copyright notice appears in all copies and
11  * that both that copyright notice and this permission notice appear
12  * in supporting documentation, and that the name of The University
13  * of Michigan not be used in advertising or publicity pertaining to
14  * distribution of the software without specific, written prior
15  * permission. This software is supplied as is without expressed or
16  * implied warranties of any kind.
17  *
18  *  Research Systems Unix Group
19  *  The University of Michigan
20  *  c/o Mike Clark
21  *  535 W. William Street
22  *  Ann Arbor, Michigan
23  *  +1-313-763-0525
24  *  netatalk@itd.umich.edu
25  *
26  */
27
28 /*!
29  * @file
30  * Part of Netatalk's AppleDouble implementatation
31  * @note We don't use inlines because a good compiler should be
32  *       able to optimize all the static funcs below.
33  * @sa include/atalk/adouble.h
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif /* HAVE_CONFIG_H */
39
40 #include <errno.h>
41 #include <sys/param.h>
42 #include <stdlib.h>
43 #include <string.h>
44
45 #include <atalk/logger.h>
46 #include <atalk/adouble.h>
47 #include <atalk/util.h>
48 #include <atalk/ea.h>
49 #include <atalk/bstrlib.h>
50 #include <atalk/bstradd.h>
51
52 #include "ad_private.h"
53
54 #ifndef MAX
55 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
56 #endif /* ! MAX */
57
58 #ifdef  HAVE_PREAD
59 # define AD_SET(a)
60 #else
61 # define AD_SET(a) a = 0
62 #endif
63
64 #define ADEDOFF_MAGIC        (0)
65 #define ADEDOFF_VERSION      (ADEDOFF_MAGIC + ADEDLEN_MAGIC)
66 #define ADEDOFF_FILLER       (ADEDOFF_VERSION + ADEDLEN_VERSION)
67 #define ADEDOFF_NENTRIES     (ADEDOFF_FILLER + ADEDLEN_FILLER)
68
69 /* initial lengths of some of the fields */
70 #define ADEDLEN_INIT     0
71
72 /* i stick things in a slightly different order than their eid order in
73  * case i ever want to separate RootInfo behaviour from the rest of the
74  * stuff. */
75
76 /* ad:v2 */
77 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
78 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
79 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
80 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
81 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
82 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
83 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
84 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
85 #define ADEDOFF_PRIVDEV      (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
86 #define ADEDOFF_PRIVINO      (ADEDOFF_PRIVDEV + ADEDLEN_PRIVDEV)
87 #define ADEDOFF_PRIVSYN      (ADEDOFF_PRIVINO + ADEDLEN_PRIVINO)
88 #define ADEDOFF_PRIVID       (ADEDOFF_PRIVSYN + ADEDLEN_PRIVSYN)
89 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRIVID + ADEDLEN_PRIVID)
90
91 /* ad:ea */
92 #define ADEDOFF_FINDERI_EA   (AD_HEADER_LEN + ADEID_NUM_EA * AD_ENTRY_LEN)
93 #define ADEDOFF_COMMENT_EA   (ADEDOFF_FINDERI_EA + ADEDLEN_FINDERI)
94 #define ADEDOFF_FILEDATESI_EA (ADEDOFF_COMMENT_EA + ADEDLEN_COMMENT)
95 #define ADEDOFF_AFPFILEI_EA  (ADEDOFF_FILEDATESI_EA + ADEDLEN_FILEDATESI)
96
97 /* this is to prevent changing timezones from causing problems with
98    localtime volumes. the screw-up is 30 years. we use a delta of 5 years */
99 #define TIMEWARP_DELTA 157680000
100
101 struct entry {
102     uint32_t id, offset, len;
103 };
104
105 /* --------------------------- */
106 static uid_t default_uid = -1;
107
108 /* Forward declarations */
109 static int ad_mkrf(char *path);
110 static int ad_header_read(struct adouble *ad, struct stat *hst);
111 static int ad_header_upgrade(struct adouble *ad, char *name);
112
113 static int ad_mkrf_ea(char *path);
114 static int ad_header_read_ea(struct adouble *ad, struct stat *hst);
115 static int ad_header_upgrade_ea(struct adouble *ad, char *name);
116
117 static struct adouble_fops ad_adouble = {
118     &ad_path,
119     &ad_mkrf,
120     &ad_rebuild_adouble_header,
121     &ad_header_read,
122     &ad_header_upgrade,
123 };
124
125 static struct adouble_fops ad_adouble_ea = {
126     &ad_path_ea,
127     &ad_mkrf_ea,
128     &ad_rebuild_adouble_header,
129     &ad_header_read_ea,
130     &ad_header_upgrade_ea,
131 };
132
133 static const struct entry entry_order2[ADEID_NUM_V2 + 1] = {
134     {ADEID_NAME,        ADEDOFF_NAME_V2,     ADEDLEN_INIT},
135     {ADEID_COMMENT,     ADEDOFF_COMMENT_V2,  ADEDLEN_INIT},
136     {ADEID_FILEDATESI,  ADEDOFF_FILEDATESI,  ADEDLEN_FILEDATESI},
137     {ADEID_FINDERI,     ADEDOFF_FINDERI_V2,  ADEDLEN_FINDERI},
138     {ADEID_DID,         ADEDOFF_DID,         ADEDLEN_DID},
139     {ADEID_AFPFILEI,    ADEDOFF_AFPFILEI,    ADEDLEN_AFPFILEI},
140     {ADEID_SHORTNAME,   ADEDOFF_SHORTNAME,   ADEDLEN_INIT},
141     {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
142     {ADEID_PRIVDEV,     ADEDOFF_PRIVDEV,     ADEDLEN_INIT},
143     {ADEID_PRIVINO,     ADEDOFF_PRIVINO,     ADEDLEN_INIT},
144     {ADEID_PRIVSYN,     ADEDOFF_PRIVSYN,     ADEDLEN_INIT},
145     {ADEID_PRIVID,      ADEDOFF_PRIVID,      ADEDLEN_INIT},
146     {ADEID_RFORK,       ADEDOFF_RFORK_V2,    ADEDLEN_INIT},
147     {0, 0, 0}
148 };
149
150 /* Using Extended Attributes */
151 static const struct entry entry_order_ea[ADEID_NUM_EA + 1] = {
152     {ADEID_FINDERI,    ADEDOFF_FINDERI_EA,    ADEDLEN_FINDERI},
153     {ADEID_COMMENT,    ADEDOFF_COMMENT_EA,    ADEDLEN_INIT},
154     {ADEID_FILEDATESI, ADEDOFF_FILEDATESI_EA, ADEDLEN_FILEDATESI},
155     {ADEID_AFPFILEI,   ADEDOFF_AFPFILEI_EA,   ADEDLEN_AFPFILEI},
156     {0, 0, 0}
157 };
158
159 static uint32_t get_eid(uint32_t eid)
160 {
161     if (eid <= 15)
162         return eid;
163     if (eid == AD_DEV)
164         return ADEID_PRIVDEV;
165     if (eid == AD_INO)
166         return ADEID_PRIVINO;
167     if (eid == AD_SYN)
168         return ADEID_PRIVSYN;
169     if (eid == AD_ID)
170         return ADEID_PRIVID;
171
172     return 0;
173 }
174
175 /* ----------------------------------- */
176 static int new_ad_header(const char *path, struct adouble *ad, int adflags)
177 {
178     const struct entry  *eid;
179     u_int16_t           ashort;
180     struct stat         st;
181
182     ad->ad_magic = AD_MAGIC;
183     ad->ad_version = ad->ad_flags & 0x0f0000;
184     if (!ad->ad_version) {
185         ad->ad_version = AD_VERSION;
186     }
187
188
189     memset(ad->ad_data, 0, sizeof(ad->ad_data));
190
191     if (ad->ad_flags == AD_VERSION2)
192         eid = entry_order2;
193     else if (ad->ad_flags == AD_VERSION_EA)
194         eid = entry_order_ea;
195     else {
196         return -1;
197     }
198
199     while (eid->id) {
200         ad->ad_eid[eid->id].ade_off = eid->offset;
201         ad->ad_eid[eid->id].ade_len = eid->len;
202         eid++;
203     }
204
205     /* put something sane in the directory finderinfo */
206     if ((adflags & ADFLAGS_DIR)) {
207         /* set default view */
208         ashort = htons(FINDERINFO_CLOSEDVIEW);
209         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
210     } else {
211         /* set default creator/type fields */
212         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"\0\0\0\0", 4);
213         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"\0\0\0\0", 4);
214     }
215
216     /* make things invisible */
217     if ((ad->ad_options & ADVOL_INVDOTS) && (*path == '.')) {
218         ashort = htons(ATTRBIT_INVISIBLE);
219         ad_setattr(ad, ashort);
220         ashort = htons(FINDERINFO_INVISIBLE);
221         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
222     }
223
224     if (lstat(path, &st) < 0)
225         return -1;
226
227     /* put something sane in the date fields */
228     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
229     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
230     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
231     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
232     return 0;
233 }
234
235 /* -------------------------------------
236    read in the entries
237 */
238 static void parse_entries(struct adouble *ad, char *buf, uint16_t nentries)
239 {
240     uint32_t   eid, len, off;
241     int        warning = 0;
242
243     /* now, read in the entry bits */
244     for (; nentries > 0; nentries-- ) {
245         memcpy(&eid, buf, sizeof( eid ));
246         eid = get_eid(ntohl(eid));
247         buf += sizeof( eid );
248         memcpy(&off, buf, sizeof( off ));
249         off = ntohl( off );
250         buf += sizeof( off );
251         memcpy(&len, buf, sizeof( len ));
252         len = ntohl( len );
253         buf += sizeof( len );
254
255         if (eid && eid < ADEID_MAX && off < sizeof(ad->ad_data) &&
256             (off + len <= sizeof(ad->ad_data) || eid == ADEID_RFORK)) {
257             ad->ad_eid[ eid ].ade_off = off;
258             ad->ad_eid[ eid ].ade_len = len;
259         } else if (!warning) {
260             warning = 1;
261             LOG(log_warning, logtype_default, "parse_entries: bogus eid: %d", eid);
262         }
263     }
264 }
265
266 /* this reads enough of the header so that we can figure out all of
267  * the entry lengths and offsets. once that's done, we just read/mmap
268  * the rest of the header in.
269  *
270  * NOTE: we're assuming that the resource fork is kept at the end of
271  *       the file. also, mmapping won't work for the hfs fs until it
272  *       understands how to mmap header files. */
273 static int ad_header_read(struct adouble *ad, struct stat *hst)
274 {
275     char                *buf = ad->ad_data;
276     u_int16_t           nentries;
277     int                 len;
278     ssize_t             header_len;
279     struct stat         st;
280
281     /* read the header */
282     if ((header_len = adf_pread( ad->ad_md, buf, sizeof(ad->ad_data), 0)) < 0) {
283         return -1;
284     }
285     if (header_len < AD_HEADER_LEN) {
286         errno = EIO;
287         return -1;
288     }
289
290     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
291     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
292     ad->ad_magic = ntohl( ad->ad_magic );
293     ad->ad_version = ntohl( ad->ad_version );
294
295     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
296         LOG(log_error, logtype_default, "ad_open: can't parse AppleDouble header.");
297         errno = EIO;
298         return -1;
299     }
300
301     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
302     nentries = ntohs( nentries );
303
304     /* read in all the entry headers. if we have more than the
305      * maximum, just hope that the rfork is specified early on. */
306     len = nentries*AD_ENTRY_LEN;
307
308     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
309         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
310
311     buf += AD_HEADER_LEN;
312     if (len > header_len - AD_HEADER_LEN) {
313         LOG(log_error, logtype_default, "ad_header_read: can't read entry info.");
314         errno = EIO;
315         return -1;
316     }
317
318     /* figure out all of the entry offsets and lengths. if we aren't
319      * able to read a resource fork entry, bail. */
320     nentries = len / AD_ENTRY_LEN;
321     parse_entries(ad, buf, nentries);
322     if (!ad_getentryoff(ad, ADEID_RFORK)
323         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
324         ) {
325         LOG(log_error, logtype_default, "ad_header_read: problem with rfork entry offset.");
326         errno = EIO;
327         return -1;
328     }
329
330     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
331         LOG(log_error, logtype_default, "ad_header_read: can't read in entries.");
332         errno = EIO;
333         return -1;
334     }
335
336     if (hst == NULL) {
337         hst = &st;
338         if (fstat(ad->ad_md->adf_fd, &st) < 0) {
339             return 1; /* fail silently */
340         }
341     }
342
343     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
344
345     return 0;
346 }
347
348 static int ad_header_read_ea(struct adouble *ad, struct stat *hst _U_)
349 {
350     uint16_t nentries;
351     int      len;
352     ssize_t  header_len;
353     char     *buf = ad->ad_data;
354
355     /* read the header */
356     if ((header_len = sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_META, ad->ad_data, AD_DATASZ_EA)) < 1) {
357         LOG(log_debug, logtype_default, "ad_header_read_ea: %s (%u)", strerror(errno), errno);
358         return -1;
359     }
360
361     if (header_len < AD_HEADER_LEN) {
362         LOG(log_error, logtype_default, "ad_header_read_ea: bogus AppleDouble header.");
363         errno = EIO;
364         return -1;
365     }
366
367     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
368     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
369
370     ad->ad_magic = ntohl( ad->ad_magic );
371     ad->ad_version = ntohl( ad->ad_version );
372
373     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
374         LOG(log_error, logtype_default, "ad_header_read_ea: wrong magic or version");
375         errno = EIO;
376         return -1;
377     }
378
379     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
380     nentries = ntohs( nentries );
381
382     /* Protect against bogus nentries */
383     len = nentries * AD_ENTRY_LEN;
384     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
385         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
386     if (len > header_len - AD_HEADER_LEN) {
387         LOG(log_error, logtype_default, "ad_header_read_ea: can't read entry info.");
388         errno = EIO;
389         return -1;
390     }
391     nentries = len / AD_ENTRY_LEN;
392
393     /* Now parse entries */
394     parse_entries(ad, buf + AD_HEADER_LEN, nentries);
395     return 0;
396 }
397
398 static int ad_mkrf(char *path)
399 {
400     char *slash;
401     /*
402      * Probably .AppleDouble doesn't exist, try to mkdir it.
403      */
404     if (NULL == ( slash = strrchr( path, '/' )) ) {
405         return -1;
406     }
407     *slash = '\0';
408     errno = 0;
409     if ( ad_mkdir( path, 0777 ) < 0 ) {
410         return -1;
411     }
412     *slash = '/';
413     return 0;
414 }
415
416 static int ad_mkrf_ea(char *path _U_)
417 {
418     AFP_PANIC("ad_mkrf_ea: dont use");
419     return 0;
420 }
421
422 /* ----------------
423    if we are root change path user/ group
424    It can be a native function for BSD cf. FAQ.Q10
425    path:  pathname to chown
426    stbuf: parent directory inode
427
428    use fstat and fchown or lchown with linux?
429 */
430 #define EMULATE_SUIDDIR
431
432 static int ad_chown(const char *path, struct stat *stbuf)
433 {
434     int ret = 0;
435 #ifdef EMULATE_SUIDDIR
436     uid_t id;
437
438     if (default_uid != (uid_t)-1) {
439         /* we are root (admin) */
440         id = (default_uid)?default_uid:stbuf->st_uid;
441         ret = lchown( path, id, stbuf->st_gid );
442     }
443 #endif
444     return ret;
445 }
446
447 #define DEFMASK 07700   /* be conservative */
448
449 /* ----------------
450    return access right and inode of path parent directory
451 */
452 static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
453 {
454     if (*mode == 0) {
455         return -1;
456     }
457     if (ad_stat(path, stbuf) != 0) {
458         *mode &= DEFMASK;
459         return -1;
460     }
461     *mode &= stbuf->st_mode;
462     return 0;
463 }
464
465 /* --------------------------- */
466 static int ad_header_upgrade(struct adouble *ad _U_, char *name _U_)
467 {
468     return 0;
469 }
470
471 static int ad_header_upgrade_ea(struct adouble *ad _U_, char *name _U_)
472 {
473     AFP_PANIC("ad_header_upgrade_ea: dont use");
474     return 0;
475 }
476
477 static int ad_open_df(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
478 {
479     struct stat st_dir;
480     int         hoflags, admode;
481     int         st_invalid = -1;
482
483     LOG(log_maxdebug, logtype_default, "ad_open_df(\"%s/%s\", adf: 0x%04x, of: 0x%04x)",
484         getcwdpath(), path, adflags, oflags);
485
486     if (ad_data_fileno(ad) == -1) {
487         hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
488         admode = mode;
489         if ((oflags & O_CREAT)) {
490             st_invalid = ad_mode_st(path, &admode, &st_dir);
491             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
492                 admode = mode;
493             }
494         }
495
496         ad->ad_data_fork.adf_fd = open(path, hoflags | O_NOFOLLOW, admode);
497
498         if (ad->ad_data_fork.adf_fd == -1) {
499             if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
500                 hoflags = oflags;
501                 ad->ad_data_fork.adf_fd = open( path, hoflags | O_NOFOLLOW, admode );
502             }
503             if (ad->ad_data_fork.adf_fd == -1 && errno == OPEN_NOFOLLOW_ERRNO) {
504                 int lsz;
505
506                 ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
507                 lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN);
508                 if (lsz <= 0) {
509                     free(ad->ad_data_fork.adf_syml);
510                     return -1;
511                 }
512                 ad->ad_data_fork.adf_syml[lsz] = 0;
513                 ad->ad_data_fork.adf_fd = -2; /* -2 means its a symlink */
514             }
515         }
516
517         if ( ad->ad_data_fork.adf_fd == -1 )
518             return -1;
519
520         AD_SET(ad->ad_data_fork.adf_off);
521         ad->ad_data_fork.adf_flags = hoflags;
522         if (!st_invalid) {
523             /* just created, set owner if admin (root) */
524             ad_chown(path, &st_dir);
525         }
526         adf_lock_init(&ad->ad_data_fork);
527     } else {
528         /* the file is already open... but */
529         if ((oflags & ( O_RDWR | O_WRONLY))
530             /* we want write access */
531             && !(ad->ad_data_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
532             /* and it was denied the first time */
533             errno = EACCES;
534             return -1;
535         }
536         /* FIXME
537          * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
538          * already open. Should we check for it? ie
539          * O_EXCL --> error
540          * O_TRUNC --> truncate the fork.
541          * idem for ressource fork.
542          */
543     }
544     ad->ad_data_fork.adf_refcount++;
545
546     return 0;
547 }
548
549 static int ad_open_hf_v2(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
550 {
551     struct stat st_dir;
552     struct stat st_meta;
553     struct stat *pst = NULL;
554     char        *ad_p;
555     int         hoflags, admode;
556     int         st_invalid = -1;
557
558     ad_p = ad->ad_ops->ad_path( path, adflags );
559
560     hoflags = oflags & ~(O_CREAT | O_EXCL);
561     if (!(adflags & ADFLAGS_RDONLY)) {
562         hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
563     }
564     ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
565     if (ad->ad_md->adf_fd < 0 ) {
566         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
567             hoflags = oflags & ~(O_CREAT | O_EXCL);
568             ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
569         }
570     }
571
572     if ( ad->ad_md->adf_fd < 0 ) {
573         if (errno == ENOENT && (oflags & O_CREAT) ) {
574             /*
575              * We're expecting to create a new adouble header file here
576              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
577              */
578             LOG(log_debug, logtype_default, "ad_open(\"%s/%s\"): creating adouble file",
579                 getcwdpath(), ad_p);
580             admode = mode;
581             errno = 0;
582             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
583             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
584                 admode = mode;
585             }
586             admode = ad_hf_mode(admode);
587             if ((errno == ENOENT)) {
588                 if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
589                     return -1;
590                 }
591                 admode = mode;
592                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
593                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
594                     admode = mode;
595                 }
596                 admode = ad_hf_mode(admode);
597             }
598             /* retry with O_CREAT */
599             ad->ad_md->adf_fd = open( ad_p, oflags,admode );
600             if ( ad->ad_md->adf_fd < 0 ) {
601                 return -1;
602             }
603             ad->ad_md->adf_flags = oflags;
604             /* just created, set owner if admin owner (root) */
605             if (!st_invalid) {
606                 ad_chown(ad_p, &st_dir);
607             }
608         } else {
609             return -1;
610         }
611     } else {
612         ad->ad_md->adf_flags = hoflags;
613         if (fstat(ad->ad_md->adf_fd, &st_meta) == 0 && st_meta.st_size == 0) {
614             /* for 0 length files, treat them as new. */
615             ad->ad_md->adf_flags |= O_TRUNC;
616         } else {
617             /* we have valid data in st_meta stat structure, reused it in ad_header_read */
618             pst = &st_meta;
619         }
620     }
621     AD_SET(ad->ad_md->adf_off);
622
623     if ((ad->ad_md->adf_flags & ( O_TRUNC | O_CREAT ))) {
624         /* This is a new adouble header file, create it */
625         if (new_ad_header(path, ad, adflags) < 0) {
626             int err = errno;
627             /* the file is already deleted, perm, whatever, so return an error */
628             errno = err;
629             return -1;
630         }
631         ad_flush(ad);
632     } else {
633         /* Read the adouble header in and parse it.*/
634         if (ad->ad_ops->ad_header_read( ad , pst) < 0
635             || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0) {
636             int err = errno;
637             errno = err;
638             return -1;
639         }
640     }
641
642     return 0;
643 }
644
645 static int ad_open_hf_ea(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
646 {
647     ssize_t rforklen;
648     int ret;
649
650     LOG(log_maxdebug, logtype_default, "ad_open_hf_ea(\"%s\", adf: 0x%04x, of: 0x%04x)",
651         abspath(path), adflags, oflags);
652
653     if ((ad->ad_md->adf_fd = open(path, O_RDONLY | O_NOFOLLOW)) == -1)
654         return -1;
655
656     /* Read the adouble header in and parse it.*/
657     if (ad->ad_ops->ad_header_read(ad, NULL) != 0) {
658         if (!(oflags & O_CREAT))
659             return -1;
660
661         /* It doesnt exist, EPERM or another error */
662         if (errno != ENOATTR && errno != ENOENT) {
663             LOG(log_error, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
664             ret = -1;
665             goto error;
666         }
667
668         /* Create one */
669         if (new_ad_header(path, ad, adflags) < 0) {
670             LOG(log_error, logtype_default, "ad_open_hf_ea: can't create new header: %s",
671                 abspath(path));
672             ret = -1;
673             goto error;
674         }
675
676         ad_flush(ad);
677     }
678
679     ad->ad_md->adf_flags = O_RDWR; /* Pretend its rw, in fact for the EA API it is */
680
681     if ((rforklen = sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_RESO, NULL, 0)) > 0)
682         ad->ad_rlen = rforklen;
683
684     return 0;
685
686 error:
687     return ret;
688 }
689
690 static int ad_open_hf(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
691 {
692     int ret = 0;
693
694     LOG(log_maxdebug, logtype_default, "ad_open_hf(\"%s/%s\", adf: 0x%04x, of: 0x%04x)",
695         getcwdpath(), path, adflags, oflags);
696
697     if (ad->ad_md->adf_refcount) {
698         /* the file is already open */
699         if ((oflags & ( O_RDWR | O_WRONLY))
700             && !(ad->ad_md->adf_flags & ( O_RDWR | O_WRONLY))) {
701             if ((adflags & ADFLAGS_HF) && ad->ad_data_fork.adf_refcount)
702                 /* We just have openend the df, so we have to close it now */
703                 ad_close(ad, ADFLAGS_DF);
704             errno = EACCES;
705             return -1;
706         }
707         ad_refresh(ad);
708         /* it's not new anymore */
709         ad->ad_md->adf_flags &= ~( O_TRUNC | O_CREAT );
710         ad->ad_md->adf_refcount++;
711         return 0;
712     }
713
714     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
715     ad->ad_rlen = 0;
716
717     switch (ad->ad_flags) {
718     case AD_VERSION2:
719         adf_lock_init(ad->ad_md);
720         ret = ad_open_hf_v2(path, adflags, oflags, mode, ad);
721         break;
722     case AD_VERSION_EA:
723         ret = ad_open_hf_ea(path, adflags, oflags, mode, ad);
724         break;
725     default:
726         ret = -1;
727         break;
728     }
729
730     ad->ad_md->adf_refcount = 1;
731
732     return ret;
733 }
734
735 #define RFORK_EA_ALLOCSIZE (128*1024) /* 128k */
736 /*!
737  * Open EA with resfork, only for AD_VERSION_EA, a nullop otherwise
738  */
739 static int ad_open_rf(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
740 {
741     int ret = 0;
742
743     if (ad->ad_flags != AD_VERSION_EA)
744         return 0;
745
746     LOG(log_maxdebug, logtype_default, "ad_open_hf_ea(\"%s\", adf: 0x%04x, of: 0x%04x)",
747         abspath(path), adflags, oflags);
748
749     if (ad->ad_resource_fork.adf_refcount) {
750         /* already open */
751         ad->ad_resource_fork.adf_flags &= ~( O_TRUNC | O_CREAT ); /* not new anymore */
752         free(ad->ad_resforkbuf);
753         ad->ad_resforkbuf = NULL;
754     }
755
756     if ((ad->ad_rlen = sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_RESO, NULL, 0)) <= 0)
757         return -1;
758
759     /* Round up and allocate buffer */
760     size_t roundup = ((ad->ad_rlen / RFORK_EA_ALLOCSIZE) + 1) * RFORK_EA_ALLOCSIZE;
761     if ((ad->ad_resforkbuf = malloc(roundup)) == NULL)
762         return -1;
763
764     ad->ad_resforkbufsize = roundup;
765
766     /* Read the EA into the buffer */
767     if (sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_META, ad->ad_resforkbuf, ad->ad_rlen) == -1)
768         return -1;
769
770     ad->ad_resource_fork.adf_refcount++;
771
772 exit:
773     if (ret != 0) {
774         free(ad->ad_resforkbuf);
775         ad->ad_resforkbuf = NULL;
776     }
777
778     return ret;
779 }
780
781 /***********************************************************************************
782  * API functions
783  ********************************************************************************* */
784
785 char *ad_path_ea( const char *path, int adflags _U_)
786 {
787     return path;
788 }
789
790 /*
791  * Put the .AppleDouble where it needs to be:
792  *
793  *      /   a/.AppleDouble/b
794  *  a/b
795  *      \   b/.AppleDouble/.Parent
796  *
797  * FIXME: should do something for pathname > MAXPATHLEN
798  */
799 char *ad_path( const char *path, int adflags)
800 {
801     static char pathbuf[ MAXPATHLEN + 1];
802     const char *slash;
803     size_t  l ;
804
805     if ( adflags & ADFLAGS_DIR ) {
806         l = strlcpy( pathbuf, path, sizeof(pathbuf));
807
808         if ( l && l < MAXPATHLEN) {
809             pathbuf[l++] = '/';
810         }
811         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
812     } else {
813         if (NULL != ( slash = strrchr( path, '/' )) ) {
814             slash++;
815             l = slash - path;
816             /* XXX we must return NULL here and test in the caller */
817             if (l > MAXPATHLEN)
818                 l = MAXPATHLEN;
819             memcpy( pathbuf, path, l);
820         } else {
821             l = 0;
822             slash = path;
823         }
824         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
825         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
826     }
827
828     return( pathbuf );
829 }
830
831 /* -------------------------
832  * Support inherited protection modes for AppleDouble files.  The supplied
833  * mode is ANDed with the parent directory's mask value in lieu of "umask",
834  * and that value is returned.
835  */
836 char *ad_dir(const char *path)
837 {
838     static char     modebuf[ MAXPATHLEN + 1];
839     char        *slash;
840     /*
841      * For a path with directories in it, remove the final component
842      * (path or subdirectory name) to get the name we want to stat.
843      * For a path which is just a filename, use "." instead.
844      */
845     slash = strrchr( path, '/' );
846     if (slash) {
847         size_t len;
848
849         len = slash - path;
850         if (len >= MAXPATHLEN) {
851             errno = ENAMETOOLONG;
852             return NULL;  /* can't do it */
853         }
854         memcpy( modebuf, path, len );
855         modebuf[len] = '\0';
856         /* is last char a '/' ? */
857         if (slash[1] == 0) {
858             slash = modebuf+ len;
859             /* remove them */
860             while (modebuf < slash && slash[-1] == '/') {
861                 --slash;
862             }
863             if (modebuf == slash) {
864                 goto use_cur;
865             }
866             *slash = '\0';
867             while (modebuf < slash && *slash != '/') {
868                 --slash;
869             }
870             if (modebuf == slash) {
871                 goto use_cur;
872             }
873             *slash = '\0';      /* remove pathname component */
874         }
875         return modebuf;
876     }
877 use_cur:
878     modebuf[0] = '.';   /* use current directory */
879     modebuf[1] = '\0';
880     return modebuf;
881 }
882
883 int ad_setfuid(const uid_t id)
884 {
885     default_uid = id;
886     return 0;
887 }
888
889 /* ---------------- */
890 uid_t ad_getfuid(void)
891 {
892     return default_uid;
893 }
894
895 /* ----------------
896    stat path parent directory
897 */
898 int ad_stat(const char *path, struct stat *stbuf)
899 {
900     char *p;
901
902     p = ad_dir(path);
903     if (!p)
904         return -1;
905     return lstat( p, stbuf );
906 }
907
908 /* ----------------
909    return access right of path parent directory
910 */
911 int ad_mode( const char *path, int mode)
912 {
913     struct stat     stbuf;
914     ad_mode_st(path, &mode, &stbuf);
915     return mode;
916 }
917
918 /*
919  * Use mkdir() with mode bits taken from ad_mode().
920  */
921 int ad_mkdir( const char *path, int mode)
922 {
923     int ret;
924     int st_invalid;
925     struct stat stbuf;
926
927     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
928         path, mode, getcwdpath());
929
930     st_invalid = ad_mode_st(path, &mode, &stbuf);
931     ret = mkdir( path, mode );
932     if (ret || st_invalid)
933         return ret;
934     ad_chown(path, &stbuf);
935
936     return ret;
937 }
938
939 void ad_init(struct adouble *ad, int flags, int options)
940 {
941     ad->ad_inited = 0;
942     ad->ad_flags = flags;
943     if (flags == AD_VERSION2) {
944         ad->ad_ops = &ad_adouble;
945         ad->ad_md = &ad->ad_resource_fork;
946     }
947     else if (flags == AD_VERSION_EA) {
948         ad->ad_ops = &ad_adouble_ea;
949         ad->ad_md = &ad->ad_metadata_fork;
950     } else {
951         LOG(log_error, logtype_default, "ad_init: unknown AD version");
952         errno = EIO;
953         return;
954     }
955
956     ad->ad_options = options;
957
958     ad_data_fileno(ad) = -1;
959     ad_reso_fileno(ad) = -1;
960     ad_meta_fileno(ad) = -1;
961
962     /* following can be read even if there's no meda data. */
963     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
964     ad->ad_rlen = 0;
965 }
966
967 static const char *adflags2logstr(int adflags)
968 {
969     int first = 1;
970     static char buf[64];
971
972     buf[0] = 0;
973
974     if (adflags & ADFLAGS_DF) {
975         strlcat(buf, "DF", 64);
976         first = 0;
977     }
978     if (adflags & ADFLAGS_RF) {
979         if (!first)
980             strlcat(buf, "|", 64);
981         strlcat(buf, "RF", 64);
982         first = 0;
983     }
984     if (adflags & ADFLAGS_HF) {
985         if (!first)
986             strlcat(buf, "|", 64);
987         strlcat(buf, "HF", 64);
988         first = 0;
989     }
990     if (adflags & ADFLAGS_NOHF) {
991         if (!first)
992             strlcat(buf, "|", 64);
993         strlcat(buf, "NOHF", 64);
994         first = 0;
995     }
996     if (adflags & ADFLAGS_DIR) {
997         if (!first)
998             strlcat(buf, "|", 64);
999         strlcat(buf, "DIR", 64);
1000         first = 0;
1001     }
1002     if (adflags & ADFLAGS_RDONLY) {
1003         if (!first)
1004             strlcat(buf, "|", 64);
1005         strlcat(buf, "RDONLY", 64);
1006         first = 0;
1007     }
1008     if (adflags & ADFLAGS_OPENFORKS) {
1009         if (!first)
1010             strlcat(buf, "|", 64);
1011         strlcat(buf, "OF", 64);
1012         first = 0;
1013     }
1014     return buf;
1015 }
1016
1017 static const char *oflags2logstr(int oflags)
1018 {
1019     int first = 1;
1020     static char buf[64];
1021
1022     buf[0] = 0;
1023
1024     if ((oflags & O_RDONLY) == O_RDONLY) {
1025         strlcat(buf, "O_RDONLY", 64);
1026         first = 0;
1027     }
1028     if (oflags & O_RDWR) {
1029         if (!first)
1030             strlcat(buf, "|", 64);
1031         strlcat(buf, "O_RDWR", 64);
1032         first = 0;
1033     }
1034     if (oflags & O_CREAT) {
1035         if (!first)
1036             strlcat(buf, "|", 64);
1037         strlcat(buf, "O_CREAT", 64);
1038         first = 0;
1039     }
1040     if (oflags & O_EXCL) {
1041         if (!first)
1042             strlcat(buf, "|", 64);
1043         strlcat(buf, "O_EXCL", 64);
1044         first = 0;
1045     }
1046     return buf;
1047 }
1048
1049 /*!
1050  * Open data-, metadata(header)- or ressource fork
1051  *
1052  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1053  * @code
1054  *      struct adoube ad;
1055  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1056  * @endcode
1057  *
1058  * @param path    Path to file or directory
1059  *
1060  * @param adflags ADFLAGS_DF:        open data fork \n
1061  *                ADFLAGS_RF:        open ressource fork \n
1062  *                ADFLAGS_HF:        open header (metadata) file \n
1063  *                ADFLAGS_NOHF:      it's not an error if header file couldn't be created \n
1064  *                ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags \n
1065  *                ADFLAGS_RDONLY:    open read only \n
1066  *                ADFLAGS_OPENFORKS: check for open forks from other processes
1067  *
1068  * @param oflags  flags passed through to open syscall: \n
1069  *                O_RDONLY: *** FIXME *** \n
1070  *                O_RDWR: *** FIXME *** \n
1071  *                O_CREAT: create fork \n
1072  *                O_EXCL: fail if exists with O_CREAT
1073  *
1074  * @param mode    passed to open with O_CREAT
1075  * @param ad      pointer to struct adouble
1076  *
1077  * @returns 0 on success
1078  *
1079  * @note It's not possible to open the header file O_RDONLY -- the read
1080  *       will fail and return an error. this refcounts things now.\n
1081  *       metadata(ressource)-fork only gets created with O_CREAT.
1082  */
1083 int ad_open(const char *path, int adflags, int oflags, int mode, struct adouble  *ad)
1084 {
1085     int ret = 0;
1086     
1087     LOG(log_debug, logtype_default, "ad_open(\"%s\", %s, %s, 0%04o)",
1088         abspath(path), adflags2logstr(adflags), oflags2logstr(oflags), mode);
1089
1090     if (ad->ad_inited != AD_INITED) {
1091         if ((ad->ad_fullpath = bfromcstr(abspath(path))) == NULL) {
1092             ret = -1;
1093             goto exit;
1094         }
1095         ad->ad_inited = AD_INITED;
1096         ad->ad_refcount = 1;
1097         ad->ad_open_forks = 0;
1098         ad->ad_resource_fork.adf_refcount = 0;
1099         ad->ad_data_fork.adf_refcount = 0;
1100         ad->ad_data_fork.adf_syml = 0;
1101     } else {
1102         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1103         /* XXX not true if we have a meta data fork ? */
1104         if ((ad->ad_resource_fork.adf_refcount > ad->ad_data_fork.adf_refcount))
1105             ad->ad_open_forks |= ATTRBIT_ROPEN;
1106     }
1107
1108     if ((adflags & ADFLAGS_DF)) {
1109         if (ad_open_df(path, adflags, oflags, mode, ad) != 0) {
1110             ret = -1;
1111             goto exit;
1112         }
1113         ad->ad_adflags |= ADFLAGS_DF;
1114     }
1115
1116     if ((adflags & ADFLAGS_HF)) {
1117         if (ad_open_hf(path, adflags, oflags, mode, ad) != 0) {
1118             ret = -1;
1119             goto exit;
1120         }
1121         ad->ad_adflags |= ADFLAGS_HF;
1122     }
1123
1124     if ((adflags & ADFLAGS_RF)) {
1125         if (ad_open_rf(path, adflags, oflags, mode, ad) != 0) {
1126             ret = -1;
1127             goto exit;
1128         }
1129         ad->ad_adflags |= ADFLAGS_RF;
1130     }
1131
1132 exit:
1133     if (ret != 0) {
1134         /* FIXME: ad_close stuff we opened before hitting an error */
1135         /* Dont forget ADFLAGS_NOHF !!! */
1136
1137         if (ad->ad_fullpath) {
1138             bdestroy(ad->ad_fullpath);
1139             ad->ad_fullpath = NULL;
1140         }
1141     }
1142
1143     return ret;
1144 }
1145
1146 /*!
1147  * @brief open metadata, possibly as root
1148  *
1149  * Return only metadata but try very hard ie at first try as user, then try as root.
1150  * Caller must pass ADFLAGS_DIR for directories.
1151  *
1152  * @param name  name of file/dir
1153  * @param flags ADFLAGS_DIR: name is a directory \n
1154  *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
1155  *
1156  * @param adp   pointer to struct adouble
1157  */
1158 int ad_metadata(const char *name, int flags, struct adouble *adp)
1159 {
1160     uid_t uid;
1161     int   ret, err, dir;
1162     int   create = O_RDONLY;
1163
1164     dir = flags & ADFLAGS_DIR;
1165
1166     if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
1167         uid = geteuid();
1168         if (seteuid(0)) {
1169             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1170             errno = EACCES;
1171             return -1;
1172         }
1173         /* we are root open read only */
1174         ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
1175         err = errno;
1176         if ( seteuid(uid) < 0) {
1177             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1178             exit(EXITERR_SYS);
1179         }
1180         errno = err;
1181     }
1182
1183     if (!ret && (ADFLAGS_OPENFORKS & flags)) {
1184         /*
1185           we need to check if the file is open by another process.
1186           it's slow so we only do it if we have to:
1187           - it's requested.
1188           - we don't already have the answer!
1189         */
1190         adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
1191     }
1192     return ret;
1193 }
1194
1195 /*
1196  * @brief openat like wrapper for ad_metadata
1197  */
1198 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1199 {
1200     int ret = 0;
1201     int cwdfd = -1;
1202
1203     if (dirfd != -1) {
1204         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1205             ret = -1;
1206             goto exit;
1207         }
1208     }
1209
1210     if (ad_metadata(name, flags, adp) < 0) {
1211         ret = -1;
1212         goto exit;
1213     }
1214
1215     if (dirfd != -1) {
1216         if (fchdir(cwdfd) != 0) {
1217             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1218             exit(EXITERR_SYS);
1219         }
1220     }
1221
1222 exit:
1223     if (cwdfd != -1)
1224         close(cwdfd);
1225
1226     return ret;
1227
1228 }
1229
1230 int ad_refresh(struct adouble *ad)
1231 {
1232
1233     if (ad_meta_fileno(ad) == -1)
1234         return -1;
1235
1236     return ad->ad_ops->ad_header_read(ad, NULL);
1237 }
1238
1239 int ad_openat(int dirfd,  /* dir fd openat like */
1240               const char *path,
1241               int adflags,
1242               int oflags,
1243               int mode,
1244               struct adouble  *ad)
1245 {
1246     int ret = 0;
1247     int cwdfd = -1;
1248
1249     if (dirfd != -1) {
1250         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1251             ret = -1;
1252             goto exit;
1253         }
1254     }
1255
1256     if (ad_open(path, adflags, oflags, mode, ad) < 0) {
1257         ret = -1;
1258         goto exit;
1259     }
1260
1261     if (dirfd != -1) {
1262         if (fchdir(cwdfd) != 0) {
1263             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1264             exit(EXITERR_SYS);
1265         }
1266     }
1267
1268 exit:
1269     if (cwdfd != -1)
1270         close(cwdfd);
1271
1272     return ret;
1273 }