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