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