]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Merge master
[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             ret = -1;
735             goto exit;
736         }
737     }
738
739     /* Round up and allocate buffer */
740     size_t roundup = ((ad->ad_rlen / RFORK_EA_ALLOCSIZE) + 1) * RFORK_EA_ALLOCSIZE;
741     if ((ad->ad_resforkbuf = malloc(roundup)) == NULL) {
742         ret = -1;
743         goto exit;
744     }
745
746     ad->ad_resforkbufsize = roundup;
747
748     /* Read the EA into the buffer */
749     if (ad->ad_rlen > 0) {
750         if (sys_lgetxattr(cfrombstr(ad->ad_fullpath), AD_EA_RESO, ad->ad_resforkbuf, ad->ad_rlen) == -1) {
751             ret = -1;
752             goto exit;
753         }       
754     }
755
756 exit:
757     if (ret != 0) {
758         free(ad->ad_resforkbuf);
759         ad->ad_resforkbuf = NULL;
760         ad->ad_rlen = 0;
761         ad->ad_resforkbufsize = 0;
762     }
763
764     return ret;
765 }
766
767 /***********************************************************************************
768  * API functions
769  ********************************************************************************* */
770
771 char *ad_path_ea( const char *path, int adflags _U_)
772 {
773     return path;
774 }
775
776 /*
777  * Put the .AppleDouble where it needs to be:
778  *
779  *      /   a/.AppleDouble/b
780  *  a/b
781  *      \   b/.AppleDouble/.Parent
782  *
783  * FIXME: should do something for pathname > MAXPATHLEN
784  */
785 char *ad_path( const char *path, int adflags)
786 {
787     static char pathbuf[ MAXPATHLEN + 1];
788     const char *slash;
789     size_t  l ;
790
791     if ( adflags & ADFLAGS_DIR ) {
792         l = strlcpy( pathbuf, path, sizeof(pathbuf));
793
794         if ( l && l < MAXPATHLEN) {
795             pathbuf[l++] = '/';
796         }
797         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
798     } else {
799         if (NULL != ( slash = strrchr( path, '/' )) ) {
800             slash++;
801             l = slash - path;
802             /* XXX we must return NULL here and test in the caller */
803             if (l > MAXPATHLEN)
804                 l = MAXPATHLEN;
805             memcpy( pathbuf, path, l);
806         } else {
807             l = 0;
808             slash = path;
809         }
810         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
811         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
812     }
813
814     return( pathbuf );
815 }
816
817 /* -------------------------
818  * Support inherited protection modes for AppleDouble files.  The supplied
819  * mode is ANDed with the parent directory's mask value in lieu of "umask",
820  * and that value is returned.
821  */
822 char *ad_dir(const char *path)
823 {
824     static char     modebuf[ MAXPATHLEN + 1];
825     char        *slash;
826     /*
827      * For a path with directories in it, remove the final component
828      * (path or subdirectory name) to get the name we want to stat.
829      * For a path which is just a filename, use "." instead.
830      */
831     slash = strrchr( path, '/' );
832     if (slash) {
833         size_t len;
834
835         len = slash - path;
836         if (len >= MAXPATHLEN) {
837             errno = ENAMETOOLONG;
838             return NULL;  /* can't do it */
839         }
840         memcpy( modebuf, path, len );
841         modebuf[len] = '\0';
842         /* is last char a '/' ? */
843         if (slash[1] == 0) {
844             slash = modebuf+ len;
845             /* remove them */
846             while (modebuf < slash && slash[-1] == '/') {
847                 --slash;
848             }
849             if (modebuf == slash) {
850                 goto use_cur;
851             }
852             *slash = '\0';
853             while (modebuf < slash && *slash != '/') {
854                 --slash;
855             }
856             if (modebuf == slash) {
857                 goto use_cur;
858             }
859             *slash = '\0';      /* remove pathname component */
860         }
861         return modebuf;
862     }
863 use_cur:
864     modebuf[0] = '.';   /* use current directory */
865     modebuf[1] = '\0';
866     return modebuf;
867 }
868
869 int ad_setfuid(const uid_t id)
870 {
871     default_uid = id;
872     return 0;
873 }
874
875 /* ---------------- */
876 uid_t ad_getfuid(void)
877 {
878     return default_uid;
879 }
880
881 /* ----------------
882    stat path parent directory
883 */
884 int ad_stat(const char *path, struct stat *stbuf)
885 {
886     char *p;
887
888     p = ad_dir(path);
889     if (!p)
890         return -1;
891     return lstat( p, stbuf );
892 }
893
894 /* ----------------
895    return access right of path parent directory
896 */
897 int ad_mode( const char *path, int mode)
898 {
899     struct stat     stbuf;
900     ad_mode_st(path, &mode, &stbuf);
901     return mode;
902 }
903
904 /*
905  * Use mkdir() with mode bits taken from ad_mode().
906  */
907 int ad_mkdir( const char *path, int mode)
908 {
909     int ret;
910     int st_invalid;
911     struct stat stbuf;
912
913     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
914         path, mode, getcwdpath());
915
916     st_invalid = ad_mode_st(path, &mode, &stbuf);
917     ret = mkdir( path, mode );
918     if (ret || st_invalid)
919         return ret;
920     ad_chown(path, &stbuf);
921
922     return ret;
923 }
924
925 void ad_init(struct adouble *ad, int flags, int options)
926 {
927     memset(ad, 0, sizeof(struct adouble));
928
929     if (flags == AD_VERSION2) {
930         ad->ad_ops = &ad_adouble;
931         ad->ad_md = &ad->ad_resource_fork;
932     }
933     else if (flags == AD_VERSION_EA) {
934         ad->ad_ops = &ad_adouble_ea;
935         ad->ad_md = &ad->ad_metadata_fork;
936     } else {
937         LOG(log_error, logtype_default, "ad_init: unknown AD version");
938         errno = EIO;
939         return;
940     }
941
942     ad->ad_flags = flags;
943     ad->ad_options = options;
944     ad_data_fileno(ad) = -1;
945     ad_reso_fileno(ad) = -1;
946     ad_meta_fileno(ad) = -1;
947     ad->ad_inited = AD_INITED;
948 }
949
950 const char *adflags2logstr(int adflags)
951 {
952     int first = 1;
953     static char buf[64];
954
955     buf[0] = 0;
956
957     if (adflags & ADFLAGS_DF) {
958         strlcat(buf, "DF", 64);
959         first = 0;
960     }
961     if (adflags & ADFLAGS_RF) {
962         if (!first)
963             strlcat(buf, "|", 64);
964         strlcat(buf, "RF", 64);
965         first = 0;
966     }
967     if (adflags & ADFLAGS_HF) {
968         if (!first)
969             strlcat(buf, "|", 64);
970         strlcat(buf, "HF", 64);
971         first = 0;
972     }
973     if (adflags & ADFLAGS_NOHF) {
974         if (!first)
975             strlcat(buf, "|", 64);
976         strlcat(buf, "NOHF", 64);
977         first = 0;
978     }
979     if (adflags & ADFLAGS_DIR) {
980         if (!first)
981             strlcat(buf, "|", 64);
982         strlcat(buf, "DIR", 64);
983         first = 0;
984     }
985     if (adflags & ADFLAGS_RDONLY) {
986         if (!first)
987             strlcat(buf, "|", 64);
988         strlcat(buf, "RDONLY", 64);
989         first = 0;
990     }
991     if (adflags & ADFLAGS_OPENFORKS) {
992         if (!first)
993             strlcat(buf, "|", 64);
994         strlcat(buf, "OF", 64);
995         first = 0;
996     }
997     return buf;
998 }
999
1000 const char *oflags2logstr(int oflags)
1001 {
1002     int first = 1;
1003     static char buf[64];
1004
1005     buf[0] = 0;
1006
1007     if (oflags == O_RDONLY) {
1008         strlcat(buf, "O_RDONLY", 64);
1009         first = 0;
1010     }
1011     if (oflags & O_RDWR) {
1012         if (!first)
1013             strlcat(buf, "|", 64);
1014         strlcat(buf, "O_RDWR", 64);
1015         first = 0;
1016     }
1017     if (oflags & O_CREAT) {
1018         if (!first)
1019             strlcat(buf, "|", 64);
1020         strlcat(buf, "O_CREAT", 64);
1021         first = 0;
1022     }
1023     if (oflags & O_EXCL) {
1024         if (!first)
1025             strlcat(buf, "|", 64);
1026         strlcat(buf, "O_EXCL", 64);
1027         first = 0;
1028     }
1029     return buf;
1030 }
1031
1032 /*!
1033  * Open data-, metadata(header)- or ressource fork
1034  *
1035  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
1036  * @code
1037  *      struct adoube ad;
1038  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1039  * @endcode
1040  *
1041  * @param path    Path to file or directory
1042  *
1043  * @param adflags ADFLAGS_DF:        open data fork \n
1044  *                ADFLAGS_RF:        open ressource fork \n
1045  *                ADFLAGS_HF:        open header (metadata) file \n
1046  *                ADFLAGS_NOHF:      it's not an error if header file couldn't be created \n
1047  *                ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags \n
1048  *                ADFLAGS_RDONLY:    open read only \n
1049  *                ADFLAGS_OPENFORKS: check for open forks from other processes
1050  *
1051  * @param oflags  flags passed through to open syscall
1052  * @param mode    passed to open with O_CREAT
1053  * @param ad      pointer to struct adouble
1054  *
1055  * @returns 0 on success, any other value indicates an error
1056  */
1057 int ad_open(const char *path, int adflags, int oflags, int mode, struct adouble  *ad)
1058 {
1059     int ret = 0;
1060     
1061     LOG(log_debug, logtype_default, "ad_open(\"%s\", %s, %s, 0%04o)",
1062         abspath(path), adflags2logstr(adflags), oflags2logstr(oflags), mode);
1063
1064     if (ad->ad_inited != AD_INITED)
1065         AFP_PANIC("ad_open: not initialized");
1066
1067     if (ad->ad_fullpath == NULL) {
1068         if ((ad->ad_fullpath = bfromcstr(abspath(path))) == NULL) {
1069             ret = -1;
1070             goto exit;
1071         }
1072     }
1073
1074     if ((adflags & ADFLAGS_DF) && !(ad->ad_adflags & ADFLAGS_DF)) {
1075         if (ad_open_df(path, adflags, oflags, mode, ad) != 0) {
1076             ret = -1;
1077             goto exit;
1078         }
1079         ad->ad_adflags |= ADFLAGS_DF;
1080     }
1081
1082     if ((adflags & ADFLAGS_HF) && !(ad->ad_adflags & ADFLAGS_HF)) {
1083         if (ad_open_hf(path, adflags, oflags, mode, ad) != 0) {
1084             ret = -1;
1085             goto exit;
1086         }
1087         ad->ad_adflags |= ADFLAGS_HF;
1088     }
1089
1090     if ((adflags & ADFLAGS_RF) && !(ad->ad_adflags & ADFLAGS_RF)) {
1091         if (ad_open_rf(path, adflags, oflags, mode, ad) != 0) {
1092             ret = -1;
1093             goto exit;
1094         }
1095         ad->ad_adflags |= ADFLAGS_RF;
1096     }
1097
1098 exit:
1099     if (ret != 0) {
1100         /* FIXME: ad_close stuff we opened before hitting an error */
1101         /* Dont forget ADFLAGS_NOHF !!! */
1102
1103         if (ad->ad_fullpath) {
1104             bdestroy(ad->ad_fullpath);
1105             ad->ad_fullpath = NULL;
1106         }
1107     }
1108
1109     return ret;
1110 }
1111
1112 /*!
1113  * @brief open metadata, possibly as root
1114  *
1115  * Return only metadata but try very hard ie at first try as user, then try as root.
1116  * Caller must pass ADFLAGS_DIR for directories.
1117  *
1118  * @param name  name of file/dir
1119  * @param flags ADFLAGS_DIR: name is a directory \n
1120  *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
1121  *
1122  * @param adp   pointer to struct adouble
1123  */
1124 int ad_metadata(const char *name, int flags, struct adouble *adp)
1125 {
1126     uid_t uid;
1127     int   ret, err, dir;
1128     int   create = O_RDONLY;
1129
1130     dir = flags & ADFLAGS_DIR;
1131
1132     if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
1133         uid = geteuid();
1134         if (seteuid(0)) {
1135             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1136             errno = EACCES;
1137             return -1;
1138         }
1139         /* we are root open read only */
1140         ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
1141         err = errno;
1142         if ( seteuid(uid) < 0) {
1143             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1144             exit(EXITERR_SYS);
1145         }
1146         errno = err;
1147     }
1148
1149     if (!ret && (ADFLAGS_OPENFORKS & flags)) {
1150         /*
1151           we need to check if the file is open by another process.
1152           it's slow so we only do it if we have to:
1153           - it's requested.
1154           - we don't already have the answer!
1155         */
1156         adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
1157     }
1158     return ret;
1159 }
1160
1161 /*
1162  * @brief openat like wrapper for ad_metadata
1163  */
1164 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1165 {
1166     int ret = 0;
1167     int cwdfd = -1;
1168
1169     if (dirfd != -1) {
1170         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1171             ret = -1;
1172             goto exit;
1173         }
1174     }
1175
1176     if (ad_metadata(name, flags, adp) < 0) {
1177         ret = -1;
1178         goto exit;
1179     }
1180
1181     if (dirfd != -1) {
1182         if (fchdir(cwdfd) != 0) {
1183             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1184             exit(EXITERR_SYS);
1185         }
1186     }
1187
1188 exit:
1189     if (cwdfd != -1)
1190         close(cwdfd);
1191
1192     return ret;
1193
1194 }
1195
1196 int ad_refresh(struct adouble *ad)
1197 {
1198
1199     if (ad_meta_fileno(ad) == -1)
1200         return -1;
1201
1202     return ad->ad_ops->ad_header_read(ad, NULL);
1203 }
1204
1205 int ad_openat(int dirfd,  /* dir fd openat like */
1206               const char *path,
1207               int adflags,
1208               int oflags,
1209               int mode,
1210               struct adouble  *ad)
1211 {
1212     int ret = 0;
1213     int cwdfd = -1;
1214
1215     if (dirfd != -1) {
1216         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1217             ret = -1;
1218             goto exit;
1219         }
1220     }
1221
1222     if (ad_open(path, adflags, oflags, mode, ad) < 0) {
1223         ret = -1;
1224         goto exit;
1225     }
1226
1227     if (dirfd != -1) {
1228         if (fchdir(cwdfd) != 0) {
1229             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1230             exit(EXITERR_SYS);
1231         }
1232     }
1233
1234 exit:
1235     if (cwdfd != -1)
1236         close(cwdfd);
1237
1238     return ret;
1239 }