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