]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Reading/writing rfork
[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_lock.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     } else {
527         /* the file is already open... but */
528         if ((oflags & ( O_RDWR | O_WRONLY))
529             /* we want write access */
530             && !(ad->ad_data_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
531             /* and it was denied the first time */
532             errno = EACCES;
533             return -1;
534         }
535         /* FIXME
536          * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
537          * already open. Should we check for it? ie
538          * O_EXCL --> error
539          * O_TRUNC --> truncate the fork.
540          * idem for ressource fork.
541          */
542     }
543
544     return 0;
545 }
546
547 static int ad_open_hf_v2(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
548 {
549     struct stat st_dir;
550     struct stat st_meta;
551     struct stat *pst = NULL;
552     char        *ad_p;
553     int         hoflags, admode;
554     int         st_invalid = -1;
555
556     ad_p = ad->ad_ops->ad_path( path, adflags );
557
558     hoflags = oflags & ~(O_CREAT | O_EXCL);
559     if (!(adflags & ADFLAGS_RDONLY)) {
560         hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
561     }
562     ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
563     if (ad->ad_md->adf_fd < 0 ) {
564         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
565             hoflags = oflags & ~(O_CREAT | O_EXCL);
566             ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
567         }
568     }
569
570     if ( ad->ad_md->adf_fd < 0 ) {
571         if (errno == ENOENT && (oflags & O_CREAT) ) {
572             /*
573              * We're expecting to create a new adouble header file here
574              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
575              */
576             LOG(log_debug, logtype_default, "ad_open(\"%s/%s\"): creating adouble file",
577                 getcwdpath(), ad_p);
578             admode = mode;
579             errno = 0;
580             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
581             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
582                 admode = mode;
583             }
584             admode = ad_hf_mode(admode);
585             if ((errno == ENOENT)) {
586                 if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
587                     return -1;
588                 }
589                 admode = mode;
590                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
591                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
592                     admode = mode;
593                 }
594                 admode = ad_hf_mode(admode);
595             }
596             /* retry with O_CREAT */
597             ad->ad_md->adf_fd = open( ad_p, oflags,admode );
598             if ( ad->ad_md->adf_fd < 0 ) {
599                 return -1;
600             }
601             ad->ad_md->adf_flags = oflags;
602             /* just created, set owner if admin owner (root) */
603             if (!st_invalid) {
604                 ad_chown(ad_p, &st_dir);
605             }
606         } else {
607             return -1;
608         }
609     } else {
610         ad->ad_md->adf_flags = hoflags;
611         if (fstat(ad->ad_md->adf_fd, &st_meta) == 0 && st_meta.st_size == 0) {
612             /* for 0 length files, treat them as new. */
613             ad->ad_md->adf_flags |= O_TRUNC;
614         } else {
615             /* we have valid data in st_meta stat structure, reused it in ad_header_read */
616             pst = &st_meta;
617         }
618     }
619     AD_SET(ad->ad_md->adf_off);
620
621     if ((ad->ad_md->adf_flags & ( O_TRUNC | O_CREAT ))) {
622         /* This is a new adouble header file, create it */
623         if (new_ad_header(path, ad, adflags) < 0) {
624             int err = errno;
625             /* the file is already deleted, perm, whatever, so return an error */
626             errno = err;
627             return -1;
628         }
629         ad_flush(ad);
630     } else {
631         /* Read the adouble header in and parse it.*/
632         if (ad->ad_ops->ad_header_read( ad , pst) < 0
633             || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0) {
634             int err = errno;
635             errno = err;
636             return -1;
637         }
638     }
639
640     return 0;
641 }
642
643 static int ad_open_hf_ea(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
644 {
645     ssize_t rforklen;
646     int ret;
647
648     LOG(log_maxdebug, logtype_default, "ad_open_hf_ea(\"%s\", adf: 0x%04x, of: 0x%04x)",
649         abspath(path), adflags, oflags);
650
651     if ((ad->ad_md->adf_fd = open(path, O_RDONLY | O_NOFOLLOW)) == -1)
652         return -1;
653
654     /* Read the adouble header in and parse it.*/
655     if (ad->ad_ops->ad_header_read(ad, NULL) != 0) {
656         if (!(oflags & O_CREAT))
657             return -1;
658
659         /* It doesnt exist, EPERM or another error */
660         if (errno != ENOATTR && errno != ENOENT) {
661             LOG(log_error, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
662             ret = -1;
663             goto error;
664         }
665
666         /* Create one */
667         if (new_ad_header(path, ad, adflags) < 0) {
668             LOG(log_error, logtype_default, "ad_open_hf_ea: can't create new header: %s",
669                 abspath(path));
670             ret = -1;
671             goto error;
672         }
673
674         ad_flush(ad);
675     }
676
677     ad->ad_md->adf_flags = O_RDWR; /* Pretend its rw, in fact for the EA API it is */
678
679     if ((rforklen = sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_RESO, NULL, 0)) > 0)
680         ad->ad_rlen = rforklen;
681
682     return 0;
683
684 error:
685     return ret;
686 }
687
688 static int ad_open_hf(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
689 {
690     int ret = 0;
691
692     LOG(log_maxdebug, logtype_default, "ad_open_hf(\"%s/%s\", adf: 0x%04x, of: 0x%04x)",
693         getcwdpath(), path, adflags, oflags);
694
695     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
696     ad->ad_rlen = 0;
697
698     switch (ad->ad_flags) {
699     case AD_VERSION2:
700         ret = ad_open_hf_v2(path, adflags, oflags, mode, ad);
701         break;
702     case AD_VERSION_EA:
703         ret = ad_open_hf_ea(path, adflags, oflags, mode, ad);
704         break;
705     default:
706         ret = -1;
707         break;
708     }
709
710     return ret;
711 }
712
713 /*!
714  * Open EA with resfork, only for AD_VERSION_EA, a nullop otherwise
715  */
716 static int ad_open_rf(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
717 {
718     int ret = 0;
719
720     if (ad->ad_flags != AD_VERSION_EA)
721         return 0;
722
723     LOG(log_debug, logtype_default, "ad_open_rf(\"%s\", adf: 0x%04x, of: 0x%04x)",
724         abspath(path), adflags, oflags);
725
726     if ((ad->ad_rlen = sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_RESO, NULL, 0)) <= 0) {
727         switch (errno) {
728         case ENOATTR:
729             ad->ad_rlen = 0;
730             break;
731         default:
732             LOG(log_warning, logtype_default, "ad_open_rf(\"%s\"): %s",
733                 abspath(path), strerror(errno));
734             return -1;
735         }
736     }
737
738     /* Round up and allocate buffer */
739     size_t roundup = ((ad->ad_rlen / RFORK_EA_ALLOCSIZE) + 1) * RFORK_EA_ALLOCSIZE;
740     if ((ad->ad_resforkbuf = malloc(roundup)) == NULL)
741         return -1;
742
743     ad->ad_resforkbufsize = roundup;
744
745     /* Read the EA into the buffer */
746     if (sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_RESO, ad->ad_resforkbuf, ad->ad_rlen) == -1)
747         return -1;
748
749     if (ret != 0) {
750         free(ad->ad_resforkbuf);
751         ad->ad_resforkbuf = NULL;
752     }
753
754     return ret;
755 }
756
757 /***********************************************************************************
758  * API functions
759  ********************************************************************************* */
760
761 char *ad_path_ea( const char *path, int adflags _U_)
762 {
763     return path;
764 }
765
766 /*
767  * Put the .AppleDouble where it needs to be:
768  *
769  *      /   a/.AppleDouble/b
770  *  a/b
771  *      \   b/.AppleDouble/.Parent
772  *
773  * FIXME: should do something for pathname > MAXPATHLEN
774  */
775 char *ad_path( const char *path, int adflags)
776 {
777     static char pathbuf[ MAXPATHLEN + 1];
778     const char *slash;
779     size_t  l ;
780
781     if ( adflags & ADFLAGS_DIR ) {
782         l = strlcpy( pathbuf, path, sizeof(pathbuf));
783
784         if ( l && l < MAXPATHLEN) {
785             pathbuf[l++] = '/';
786         }
787         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
788     } else {
789         if (NULL != ( slash = strrchr( path, '/' )) ) {
790             slash++;
791             l = slash - path;
792             /* XXX we must return NULL here and test in the caller */
793             if (l > MAXPATHLEN)
794                 l = MAXPATHLEN;
795             memcpy( pathbuf, path, l);
796         } else {
797             l = 0;
798             slash = path;
799         }
800         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
801         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
802     }
803
804     return( pathbuf );
805 }
806
807 /* -------------------------
808  * Support inherited protection modes for AppleDouble files.  The supplied
809  * mode is ANDed with the parent directory's mask value in lieu of "umask",
810  * and that value is returned.
811  */
812 char *ad_dir(const char *path)
813 {
814     static char     modebuf[ MAXPATHLEN + 1];
815     char        *slash;
816     /*
817      * For a path with directories in it, remove the final component
818      * (path or subdirectory name) to get the name we want to stat.
819      * For a path which is just a filename, use "." instead.
820      */
821     slash = strrchr( path, '/' );
822     if (slash) {
823         size_t len;
824
825         len = slash - path;
826         if (len >= MAXPATHLEN) {
827             errno = ENAMETOOLONG;
828             return NULL;  /* can't do it */
829         }
830         memcpy( modebuf, path, len );
831         modebuf[len] = '\0';
832         /* is last char a '/' ? */
833         if (slash[1] == 0) {
834             slash = modebuf+ len;
835             /* remove them */
836             while (modebuf < slash && slash[-1] == '/') {
837                 --slash;
838             }
839             if (modebuf == slash) {
840                 goto use_cur;
841             }
842             *slash = '\0';
843             while (modebuf < slash && *slash != '/') {
844                 --slash;
845             }
846             if (modebuf == slash) {
847                 goto use_cur;
848             }
849             *slash = '\0';      /* remove pathname component */
850         }
851         return modebuf;
852     }
853 use_cur:
854     modebuf[0] = '.';   /* use current directory */
855     modebuf[1] = '\0';
856     return modebuf;
857 }
858
859 int ad_setfuid(const uid_t id)
860 {
861     default_uid = id;
862     return 0;
863 }
864
865 /* ---------------- */
866 uid_t ad_getfuid(void)
867 {
868     return default_uid;
869 }
870
871 /* ----------------
872    stat path parent directory
873 */
874 int ad_stat(const char *path, struct stat *stbuf)
875 {
876     char *p;
877
878     p = ad_dir(path);
879     if (!p)
880         return -1;
881     return lstat( p, stbuf );
882 }
883
884 /* ----------------
885    return access right of path parent directory
886 */
887 int ad_mode( const char *path, int mode)
888 {
889     struct stat     stbuf;
890     ad_mode_st(path, &mode, &stbuf);
891     return mode;
892 }
893
894 /*
895  * Use mkdir() with mode bits taken from ad_mode().
896  */
897 int ad_mkdir( const char *path, int mode)
898 {
899     int ret;
900     int st_invalid;
901     struct stat stbuf;
902
903     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
904         path, mode, getcwdpath());
905
906     st_invalid = ad_mode_st(path, &mode, &stbuf);
907     ret = mkdir( path, mode );
908     if (ret || st_invalid)
909         return ret;
910     ad_chown(path, &stbuf);
911
912     return ret;
913 }
914
915 void ad_init(struct adouble *ad, int flags, int options)
916 {
917     memset(ad, 0, sizeof(struct adouble));
918
919     if (flags == AD_VERSION2) {
920         ad->ad_ops = &ad_adouble;
921         ad->ad_md = &ad->ad_resource_fork;
922     }
923     else if (flags == AD_VERSION_EA) {
924         ad->ad_ops = &ad_adouble_ea;
925         ad->ad_md = &ad->ad_metadata_fork;
926     } else {
927         LOG(log_error, logtype_default, "ad_init: unknown AD version");
928         errno = EIO;
929         return;
930     }
931
932     ad->ad_flags = flags;
933     ad->ad_options = options;
934     ad_data_fileno(ad) = -1;
935     ad_reso_fileno(ad) = -1;
936     ad_meta_fileno(ad) = -1;
937     ad->ad_inited = AD_INITED;
938 }
939
940 static const char *adflags2logstr(int adflags)
941 {
942     int first = 1;
943     static char buf[64];
944
945     buf[0] = 0;
946
947     if (adflags & ADFLAGS_DF) {
948         strlcat(buf, "DF", 64);
949         first = 0;
950     }
951     if (adflags & ADFLAGS_RF) {
952         if (!first)
953             strlcat(buf, "|", 64);
954         strlcat(buf, "RF", 64);
955         first = 0;
956     }
957     if (adflags & ADFLAGS_HF) {
958         if (!first)
959             strlcat(buf, "|", 64);
960         strlcat(buf, "HF", 64);
961         first = 0;
962     }
963     if (adflags & ADFLAGS_NOHF) {
964         if (!first)
965             strlcat(buf, "|", 64);
966         strlcat(buf, "NOHF", 64);
967         first = 0;
968     }
969     if (adflags & ADFLAGS_DIR) {
970         if (!first)
971             strlcat(buf, "|", 64);
972         strlcat(buf, "DIR", 64);
973         first = 0;
974     }
975     if (adflags & ADFLAGS_RDONLY) {
976         if (!first)
977             strlcat(buf, "|", 64);
978         strlcat(buf, "RDONLY", 64);
979         first = 0;
980     }
981     if (adflags & ADFLAGS_OPENFORKS) {
982         if (!first)
983             strlcat(buf, "|", 64);
984         strlcat(buf, "OF", 64);
985         first = 0;
986     }
987     return buf;
988 }
989
990 static const char *oflags2logstr(int oflags)
991 {
992     int first = 1;
993     static char buf[64];
994
995     buf[0] = 0;
996
997     if (oflags == O_RDONLY) {
998         strlcat(buf, "O_RDONLY", 64);
999         first = 0;
1000     }
1001     if (oflags & O_RDWR) {
1002         if (!first)
1003             strlcat(buf, "|", 64);
1004         strlcat(buf, "O_RDWR", 64);
1005         first = 0;
1006     }
1007     if (oflags & O_CREAT) {
1008         if (!first)
1009             strlcat(buf, "|", 64);
1010         strlcat(buf, "O_CREAT", 64);
1011         first = 0;
1012     }
1013     if (oflags & O_EXCL) {
1014         if (!first)
1015             strlcat(buf, "|", 64);
1016         strlcat(buf, "O_EXCL", 64);
1017         first = 0;
1018     }
1019     return buf;
1020 }
1021
1022 /*!
1023  * Open data-, metadata(header)- or ressource fork
1024  *
1025  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1026  * @code
1027  *      struct adoube ad;
1028  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1029  * @endcode
1030  *
1031  * @param path    Path to file or directory
1032  *
1033  * @param adflags ADFLAGS_DF:        open data fork \n
1034  *                ADFLAGS_RF:        open ressource fork \n
1035  *                ADFLAGS_HF:        open header (metadata) file \n
1036  *                ADFLAGS_NOHF:      it's not an error if header file couldn't be created \n
1037  *                ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags \n
1038  *                ADFLAGS_RDONLY:    open read only \n
1039  *                ADFLAGS_OPENFORKS: check for open forks from other processes
1040  *
1041  * @param oflags  flags passed through to open syscall: \n
1042  *                O_RDONLY: *** FIXME *** \n
1043  *                O_RDWR: *** FIXME *** \n
1044  *                O_CREAT: create fork \n
1045  *                O_EXCL: fail if exists with O_CREAT
1046  *
1047  * @param mode    passed to open with O_CREAT
1048  * @param ad      pointer to struct adouble
1049  *
1050  * @returns 0 on success
1051  *
1052  * @note It's not possible to open the header file O_RDONLY -- the read
1053  *       will fail and return an error. this refcounts things now.\n
1054  *       metadata(ressource)-fork only gets created with O_CREAT.
1055  */
1056 int ad_open(const char *path, int adflags, int oflags, int mode, struct adouble  *ad)
1057 {
1058     int ret = 0;
1059     
1060     LOG(log_debug, logtype_default, "ad_open(\"%s\", %s, %s, 0%04o)",
1061         abspath(path), adflags2logstr(adflags), oflags2logstr(oflags), mode);
1062
1063     if (ad->ad_inited != AD_INITED)
1064         AFP_PANIC("ad_open: not initialized");
1065
1066     if (ad->ad_fullpath == NULL) {
1067         if ((ad->ad_fullpath = bfromcstr(abspath(path))) == NULL) {
1068             ret = -1;
1069             goto exit;
1070         }
1071     }
1072
1073     ad->ad_refcount++;
1074
1075     if ((adflags & ADFLAGS_DF)) {
1076         if (ad_open_df(path, adflags, oflags, mode, ad) != 0) {
1077             ret = -1;
1078             goto exit;
1079         }
1080         ad->ad_adflags |= ADFLAGS_DF;
1081     }
1082
1083     if ((adflags & ADFLAGS_HF)) {
1084         if (ad_open_hf(path, adflags, oflags, mode, ad) != 0) {
1085             ret = -1;
1086             goto exit;
1087         }
1088         ad->ad_adflags |= ADFLAGS_HF;
1089     }
1090
1091     if ((adflags & ADFLAGS_RF)) {
1092         if (ad_open_rf(path, adflags, oflags, mode, ad) != 0) {
1093             ret = -1;
1094             goto exit;
1095         }
1096         ad->ad_adflags |= ADFLAGS_RF;
1097     }
1098
1099 exit:
1100     if (ret != 0) {
1101         /* FIXME: ad_close stuff we opened before hitting an error */
1102         /* Dont forget ADFLAGS_NOHF !!! */
1103
1104         if (ad->ad_fullpath) {
1105             bdestroy(ad->ad_fullpath);
1106             ad->ad_fullpath = NULL;
1107         }
1108     }
1109
1110     return ret;
1111 }
1112
1113 /*!
1114  * @brief open metadata, possibly as root
1115  *
1116  * Return only metadata but try very hard ie at first try as user, then try as root.
1117  * Caller must pass ADFLAGS_DIR for directories.
1118  *
1119  * @param name  name of file/dir
1120  * @param flags ADFLAGS_DIR: name is a directory \n
1121  *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
1122  *
1123  * @param adp   pointer to struct adouble
1124  */
1125 int ad_metadata(const char *name, int flags, struct adouble *adp)
1126 {
1127     uid_t uid;
1128     int   ret, err, dir;
1129     int   create = O_RDONLY;
1130
1131     dir = flags & ADFLAGS_DIR;
1132
1133     if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
1134         uid = geteuid();
1135         if (seteuid(0)) {
1136             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1137             errno = EACCES;
1138             return -1;
1139         }
1140         /* we are root open read only */
1141         ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
1142         err = errno;
1143         if ( seteuid(uid) < 0) {
1144             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1145             exit(EXITERR_SYS);
1146         }
1147         errno = err;
1148     }
1149
1150     if (!ret && (ADFLAGS_OPENFORKS & flags)) {
1151         /*
1152           we need to check if the file is open by another process.
1153           it's slow so we only do it if we have to:
1154           - it's requested.
1155           - we don't already have the answer!
1156         */
1157         adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
1158     }
1159     return ret;
1160 }
1161
1162 /*
1163  * @brief openat like wrapper for ad_metadata
1164  */
1165 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1166 {
1167     int ret = 0;
1168     int cwdfd = -1;
1169
1170     if (dirfd != -1) {
1171         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1172             ret = -1;
1173             goto exit;
1174         }
1175     }
1176
1177     if (ad_metadata(name, flags, adp) < 0) {
1178         ret = -1;
1179         goto exit;
1180     }
1181
1182     if (dirfd != -1) {
1183         if (fchdir(cwdfd) != 0) {
1184             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1185             exit(EXITERR_SYS);
1186         }
1187     }
1188
1189 exit:
1190     if (cwdfd != -1)
1191         close(cwdfd);
1192
1193     return ret;
1194
1195 }
1196
1197 int ad_refresh(struct adouble *ad)
1198 {
1199
1200     if (ad_meta_fileno(ad) == -1)
1201         return -1;
1202
1203     return ad->ad_ops->ad_header_read(ad, NULL);
1204 }
1205
1206 int ad_openat(int dirfd,  /* dir fd openat like */
1207               const char *path,
1208               int adflags,
1209               int oflags,
1210               int mode,
1211               struct adouble  *ad)
1212 {
1213     int ret = 0;
1214     int cwdfd = -1;
1215
1216     if (dirfd != -1) {
1217         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1218             ret = -1;
1219             goto exit;
1220         }
1221     }
1222
1223     if (ad_open(path, adflags, oflags, mode, ad) < 0) {
1224         ret = -1;
1225         goto exit;
1226     }
1227
1228     if (dirfd != -1) {
1229         if (fchdir(cwdfd) != 0) {
1230             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1231             exit(EXITERR_SYS);
1232         }
1233     }
1234
1235 exit:
1236     if (cwdfd != -1)
1237         close(cwdfd);
1238
1239     return ret;
1240 }