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