]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Successfully created first EA adouble object
[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
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
369     /* read the header */
370     if ((header_len = sys_fgetxattr(ad->ad_md->adf_fd, AD_EA_META, ad->ad_data, AD_DATASZ_EA)) < 1) {
371         LOG(log_debug, logtype_default, "ad_header_read_ea: %s (%u)", strerror(errno), errno);
372         return -1;
373     }
374
375     if (header_len < AD_HEADER_LEN) {
376         LOG(log_error, logtype_default, "ad_header_read_ea: bogus AppleDouble header.");
377         errno = EIO;
378         return -1;
379     }
380
381     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
382     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
383
384     ad->ad_magic = ntohl( ad->ad_magic );
385     ad->ad_version = ntohl( ad->ad_version );
386
387     if ((ad->ad_magic != AD_MAGIC) || (ad->ad_version != AD_VERSION2)) {
388         LOG(log_error, logtype_default, "ad_header_read_ea: wrong magic or version");
389         errno = EIO;
390         return -1;
391     }
392
393     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
394     nentries = ntohs( nentries );
395
396     /* Protect against bogus nentries */
397     len = nentries * AD_ENTRY_LEN;
398     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
399         len = sizeof(ad->ad_data) - AD_HEADER_LEN;
400     if (len > header_len - AD_HEADER_LEN) {
401         LOG(log_error, logtype_default, "ad_header_read_ea: can't read entry info.");
402         errno = EIO;
403         return -1;
404     }
405     nentries = len / AD_ENTRY_LEN;
406
407     /* Now parse entries */
408     parse_entries(ad, buf + AD_HEADER_LEN, nentries);
409     return 0;
410 }
411
412 static int ad_mkrf(char *path)
413 {
414     char *slash;
415     /*
416      * Probably .AppleDouble doesn't exist, try to mkdir it.
417      */
418     if (NULL == ( slash = strrchr( path, '/' )) ) {
419         return -1;
420     }
421     *slash = '\0';
422     errno = 0;
423     if ( ad_mkdir( path, 0777 ) < 0 ) {
424         return -1;
425     }
426     *slash = '/';
427     return 0;
428 }
429
430 static int ad_mkrf_ea(char *path _U_)
431 {
432     AFP_PANIC("ad_mkrf_ea: dont use");
433     return 0;
434 }
435
436 /* ----------------
437    if we are root change path user/ group
438    It can be a native function for BSD cf. FAQ.Q10
439    path:  pathname to chown
440    stbuf: parent directory inode
441
442    use fstat and fchown or lchown with linux?
443 */
444 #define EMULATE_SUIDDIR
445
446 static int ad_chown(const char *path, struct stat *stbuf)
447 {
448     int ret = 0;
449 #ifdef EMULATE_SUIDDIR
450     uid_t id;
451
452     if (default_uid != (uid_t)-1) {
453         /* we are root (admin) */
454         id = (default_uid)?default_uid:stbuf->st_uid;
455         ret = lchown( path, id, stbuf->st_gid );
456     }
457 #endif
458     return ret;
459 }
460
461 #define DEFMASK 07700   /* be conservative */
462
463 /* ----------------
464    return access right and inode of path parent directory
465 */
466 static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
467 {
468     if (*mode == 0) {
469         return -1;
470     }
471     if (ad_stat(path, stbuf) != 0) {
472         *mode &= DEFMASK;
473         return -1;
474     }
475     *mode &= stbuf->st_mode;
476     return 0;
477 }
478
479 /* ----------------- */
480 static int ad_error(struct adouble *ad, int adflags)
481 {
482     int err = errno;
483     if ((adflags & ADFLAGS_NOHF)) {
484         /* FIXME double check : set header offset ?*/
485         return 0;
486     }
487     if ((adflags & ADFLAGS_DF)) {
488         ad_close( ad, ADFLAGS_DF );
489         err = errno;
490     }
491     return -1 ;
492 }
493
494 /* --------------------------- */
495 static int ad_header_upgrade(struct adouble *ad _U_, char *name _U_)
496 {
497     return 0;
498 }
499
500 static int ad_header_upgrade_ea(struct adouble *ad _U_, char *name _U_)
501 {
502     AFP_PANIC("ad_header_upgrade_ea: dont use");
503     return 0;
504 }
505
506 static int ad_open_df(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
507 {
508     struct stat st_dir;
509     int         hoflags, admode;
510     int         st_invalid = -1;
511
512     LOG(log_maxdebug, logtype_default, "ad_open_df(\"%s/%s\", adf: 0x%04x, of: 0x%04x)",
513         getcwdpath(), path, adflags, oflags);
514
515     if (ad_data_fileno(ad) == -1) {
516         hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
517         admode = mode;
518         if ((oflags & O_CREAT)) {
519             st_invalid = ad_mode_st(path, &admode, &st_dir);
520             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
521                 admode = mode;
522             }
523         }
524
525         ad->ad_data_fork.adf_fd = open(path, hoflags | O_NOFOLLOW, admode);
526
527         if (ad->ad_data_fork.adf_fd == -1) {
528             if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
529                 hoflags = oflags;
530                 ad->ad_data_fork.adf_fd = open( path, hoflags | O_NOFOLLOW, admode );
531             }
532             if (ad->ad_data_fork.adf_fd == -1 && errno == OPEN_NOFOLLOW_ERRNO) {
533                 int lsz;
534
535                 ad->ad_data_fork.adf_syml = malloc(MAXPATHLEN+1);
536                 lsz = readlink(path, ad->ad_data_fork.adf_syml, MAXPATHLEN);
537                 if (lsz <= 0) {
538                     free(ad->ad_data_fork.adf_syml);
539                     return -1;
540                 }
541                 ad->ad_data_fork.adf_syml[lsz] = 0;
542                 ad->ad_data_fork.adf_fd = -2; /* -2 means its a symlink */
543             }
544         }
545
546         if ( ad->ad_data_fork.adf_fd == -1 )
547             return -1;
548
549         AD_SET(ad->ad_data_fork.adf_off);
550         ad->ad_data_fork.adf_flags = hoflags;
551         if (!st_invalid) {
552             /* just created, set owner if admin (root) */
553             ad_chown(path, &st_dir);
554         }
555         adf_lock_init(&ad->ad_data_fork);
556     } else {
557         /* the file is already open... but */
558         if ((oflags & ( O_RDWR | O_WRONLY))
559             /* we want write access */
560             && !(ad->ad_data_fork.adf_flags & ( O_RDWR | O_WRONLY))) {
561             /* and it was denied the first time */
562             errno = EACCES;
563             return -1;
564         }
565         /* FIXME
566          * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
567          * already open. Should we check for it? ie
568          * O_EXCL --> error
569          * O_TRUNC --> truncate the fork.
570          * idem for ressource fork.
571          */
572     }
573     ad->ad_data_fork.adf_refcount++;
574
575     return 0;
576 }
577
578 static int ad_open_hf_v2(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
579 {
580     struct stat st_dir;
581     struct stat st_meta;
582     struct stat *pst = NULL;
583     char        *ad_p;
584     int         hoflags, admode;
585     int         st_invalid = -1;
586
587     ad_p = ad->ad_ops->ad_path( path, adflags );
588
589     hoflags = oflags & ~(O_CREAT | O_EXCL);
590     if (!(adflags & ADFLAGS_RDONLY)) {
591         hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
592     }
593     ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
594     if (ad->ad_md->adf_fd < 0 ) {
595         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
596             hoflags = oflags & ~(O_CREAT | O_EXCL);
597             ad->ad_md->adf_fd = open( ad_p, hoflags | O_NOFOLLOW, 0 );
598         }
599     }
600
601     if ( ad->ad_md->adf_fd < 0 ) {
602         if (errno == ENOENT && (oflags & O_CREAT) ) {
603             /*
604              * We're expecting to create a new adouble header file here
605              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
606              */
607             LOG(log_debug, logtype_default, "ad_open(\"%s/%s\"): creating adouble file",
608                 getcwdpath(), ad_p);
609             admode = mode;
610             errno = 0;
611             st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
612             if ((ad->ad_options & ADVOL_UNIXPRIV)) {
613                 admode = mode;
614             }
615             admode = ad_hf_mode(admode);
616             if ((errno == ENOENT)) {
617                 if (ad->ad_ops->ad_mkrf( ad_p) < 0) {
618                     return ad_error(ad, adflags);
619                 }
620                 admode = mode;
621                 st_invalid = ad_mode_st(ad_p, &admode, &st_dir);
622                 if ((ad->ad_options & ADVOL_UNIXPRIV)) {
623                     admode = mode;
624                 }
625                 admode = ad_hf_mode(admode);
626             }
627             /* retry with O_CREAT */
628             ad->ad_md->adf_fd = open( ad_p, oflags,admode );
629             if ( ad->ad_md->adf_fd < 0 ) {
630                 return ad_error(ad, adflags);
631             }
632             ad->ad_md->adf_flags = oflags;
633             /* just created, set owner if admin owner (root) */
634             if (!st_invalid) {
635                 ad_chown(ad_p, &st_dir);
636             }
637         } else {
638             return ad_error(ad, adflags);
639         }
640     } else {
641         ad->ad_md->adf_flags = hoflags;
642         if (fstat(ad->ad_md->adf_fd, &st_meta) == 0 && st_meta.st_size == 0) {
643             /* for 0 length files, treat them as new. */
644             ad->ad_md->adf_flags |= O_TRUNC;
645         } else {
646             /* we have valid data in st_meta stat structure, reused it in ad_header_read */
647             pst = &st_meta;
648         }
649     }
650     AD_SET(ad->ad_md->adf_off);
651
652     if ((ad->ad_md->adf_flags & ( O_TRUNC | O_CREAT ))) {
653         /* This is a new adouble header file, create it */
654         if (new_ad_header(path, ad, adflags) < 0) {
655             int err = errno;
656             /* the file is already deleted, perm, whatever, so return an error */
657             ad_close(ad, adflags);
658             errno = err;
659             return -1;
660         }
661         ad_flush(ad);
662     } else {
663         /* Read the adouble header in and parse it.*/
664         if (ad->ad_ops->ad_header_read( ad , pst) < 0
665             || ad->ad_ops->ad_header_upgrade(ad, ad_p) < 0) {
666             int err = errno;
667             ad_close( ad, adflags );
668             errno = err;
669             return -1;
670         }
671     }
672
673     return 0;
674 }
675
676 static int ad_open_hf_ea(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
677 {
678     ssize_t rforklen;
679     int ret;
680     int err;
681
682     LOG(log_maxdebug, logtype_default, "ad_open_hf_ea(\"%s/%s\", adf: 0x%04x, of: 0x%04x)",
683         getcwdpath(), path, adflags, oflags);
684
685     if ((ad->ad_md->adf_fd = open(path, O_RDONLY | O_NOFOLLOW)) == -1)
686         return -1;
687
688     /* Read the adouble header in and parse it.*/
689     if (ad->ad_ops->ad_header_read(ad, NULL) != 0) {
690         if (!(oflags & O_CREAT)) {
691             ret = 0;
692             goto error;
693         }
694
695         /* It doesnt exist, EPERM or another error */
696         if (errno != ENOATTR) {
697             LOG(log_maxdebug, logtype_default, "ad_open_hf_ea: unexpected: %s", strerror(errno));
698             ret = -1;
699             goto error;
700         }
701
702         /* Create one */
703         if (new_ad_header(path, ad, adflags) < 0) {
704             ret = -1;
705             goto error;
706         }
707
708         ad_flush(ad);
709     }
710
711     ad->ad_md->adf_flags = O_RDWR; /* Pretend its rw, in fact for the EA API it is */
712
713     if ((rforklen = sys_fgetxattr(ad->ad_md->adf_fd, AD_EA_RESO, NULL, 0)) > 0)
714         ad->ad_rlen = rforklen;
715
716     return 0;
717
718 error:
719     err = errno;
720     ad_close(ad, adflags);
721     errno = err;
722     LOG(log_error, logtype_default, "ad_open_hf_ea: error: %s", strerror(errno));
723     return ret;
724 }
725
726 static int ad_open_hf(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
727 {
728     int ret = 0;
729
730     LOG(log_maxdebug, logtype_default, "ad_open_hf(\"%s/%s\", adf: 0x%04x, of: 0x%04x)",
731         getcwdpath(), path, adflags, oflags);
732
733     if (ad_meta_fileno(ad) != -1) { /* the file is already open */
734         LOG(log_maxdebug, logtype_default,"the file is already open");
735         if ((oflags & ( O_RDWR | O_WRONLY))
736             && !(ad->ad_md->adf_flags & ( O_RDWR | O_WRONLY))) {
737             if ((adflags & ADFLAGS_HF) && ad->ad_data_fork.adf_refcount)
738                 /* We just have openend the df, so we have to close it now */
739                 ad_close(ad, ADFLAGS_DF);
740             errno = EACCES;
741             return -1;
742         }
743         ad_refresh(ad);
744         /* it's not new anymore */
745         ad->ad_md->adf_flags &= ~( O_TRUNC | O_CREAT );
746         ad->ad_md->adf_refcount++;
747         return 0;
748     }
749
750     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
751     ad->ad_rlen = 0;
752
753     switch (ad->ad_flags) {
754     case AD_VERSION2:
755         ret = ad_open_hf_v2(path, adflags, oflags, mode, ad);
756         break;
757     case AD_VERSION_EA:
758         ret = ad_open_hf_ea(path, adflags, oflags, mode, ad);
759         break;
760     default:
761         ret = -1;
762         break;
763     }
764
765     ad->ad_md->adf_refcount = 1;
766     adf_lock_init(ad->ad_md);
767
768     return ret;
769 }
770
771 static int ad_open_rf(const char *path, int adflags, int oflags, int mode, struct adouble *ad)
772 {
773     return 0;
774 }
775
776 /***********************************************************************************
777  * API functions
778  ********************************************************************************* */
779
780 char *ad_path_ea( const char *path, int adflags _U_)
781 {
782     return path;
783 }
784
785 /*
786  * Put the .AppleDouble where it needs to be:
787  *
788  *      /   a/.AppleDouble/b
789  *  a/b
790  *      \   b/.AppleDouble/.Parent
791  *
792  * FIXME: should do something for pathname > MAXPATHLEN
793  */
794 char *ad_path( const char *path, int adflags)
795 {
796     static char pathbuf[ MAXPATHLEN + 1];
797     const char *slash;
798     size_t  l ;
799
800     if ( adflags & ADFLAGS_DIR ) {
801         l = strlcpy( pathbuf, path, sizeof(pathbuf));
802
803         if ( l && l < MAXPATHLEN) {
804             pathbuf[l++] = '/';
805         }
806         strlcpy(pathbuf +l, ".AppleDouble/.Parent", sizeof(pathbuf) -l);
807     } else {
808         if (NULL != ( slash = strrchr( path, '/' )) ) {
809             slash++;
810             l = slash - path;
811             /* XXX we must return NULL here and test in the caller */
812             if (l > MAXPATHLEN)
813                 l = MAXPATHLEN;
814             memcpy( pathbuf, path, l);
815         } else {
816             l = 0;
817             slash = path;
818         }
819         l += strlcpy( pathbuf +l, ".AppleDouble/", sizeof(pathbuf) -l);
820         strlcpy( pathbuf + l, slash, sizeof(pathbuf) -l);
821     }
822
823     return( pathbuf );
824 }
825
826 /* -------------------------
827  * Support inherited protection modes for AppleDouble files.  The supplied
828  * mode is ANDed with the parent directory's mask value in lieu of "umask",
829  * and that value is returned.
830  */
831 char *ad_dir(const char *path)
832 {
833     static char     modebuf[ MAXPATHLEN + 1];
834     char        *slash;
835     /*
836      * For a path with directories in it, remove the final component
837      * (path or subdirectory name) to get the name we want to stat.
838      * For a path which is just a filename, use "." instead.
839      */
840     slash = strrchr( path, '/' );
841     if (slash) {
842         size_t len;
843
844         len = slash - path;
845         if (len >= MAXPATHLEN) {
846             errno = ENAMETOOLONG;
847             return NULL;  /* can't do it */
848         }
849         memcpy( modebuf, path, len );
850         modebuf[len] = '\0';
851         /* is last char a '/' ? */
852         if (slash[1] == 0) {
853             slash = modebuf+ len;
854             /* remove them */
855             while (modebuf < slash && slash[-1] == '/') {
856                 --slash;
857             }
858             if (modebuf == slash) {
859                 goto use_cur;
860             }
861             *slash = '\0';
862             while (modebuf < slash && *slash != '/') {
863                 --slash;
864             }
865             if (modebuf == slash) {
866                 goto use_cur;
867             }
868             *slash = '\0';      /* remove pathname component */
869         }
870         return modebuf;
871     }
872 use_cur:
873     modebuf[0] = '.';   /* use current directory */
874     modebuf[1] = '\0';
875     return modebuf;
876 }
877
878 int ad_setfuid(const uid_t id)
879 {
880     default_uid = id;
881     return 0;
882 }
883
884 /* ---------------- */
885 uid_t ad_getfuid(void)
886 {
887     return default_uid;
888 }
889
890 /* ----------------
891    stat path parent directory
892 */
893 int ad_stat(const char *path, struct stat *stbuf)
894 {
895     char *p;
896
897     p = ad_dir(path);
898     if (!p)
899         return -1;
900     return lstat( p, stbuf );
901 }
902
903 /* ----------------
904    return access right of path parent directory
905 */
906 int ad_mode( const char *path, int mode)
907 {
908     struct stat     stbuf;
909     ad_mode_st(path, &mode, &stbuf);
910     return mode;
911 }
912
913 /*
914  * Use mkdir() with mode bits taken from ad_mode().
915  */
916 int ad_mkdir( const char *path, int mode)
917 {
918     int ret;
919     int st_invalid;
920     struct stat stbuf;
921
922     LOG(log_debug, logtype_default, "ad_mkdir(\"%s\", %04o) {cwd: \"%s\"}",
923         path, mode, getcwdpath());
924
925     st_invalid = ad_mode_st(path, &mode, &stbuf);
926     ret = mkdir( path, mode );
927     if (ret || st_invalid)
928         return ret;
929     ad_chown(path, &stbuf);
930
931     return ret;
932 }
933
934 void ad_init(struct adouble *ad, int flags, int options)
935 {
936     ad->ad_inited = 0;
937     ad->ad_flags = flags;
938     if (flags == AD_VERSION2) {
939         ad->ad_ops = &ad_adouble;
940         ad->ad_md = &ad->ad_resource_fork;
941     }
942     else if (flags == AD_VERSION_EA) {
943         ad->ad_ops = &ad_adouble_ea;
944         ad->ad_md = &ad->ad_metadata_fork;
945     } else {
946         LOG(log_error, logtype_default, "ad_init: unknown AD version");
947         errno = EIO;
948         return;
949     }
950
951     ad->ad_options = options;
952
953     ad_data_fileno(ad) = -1;
954     ad_reso_fileno(ad) = -1;
955     ad_meta_fileno(ad) = -1;
956
957     /* following can be read even if there's no meda data. */
958     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
959     ad->ad_rlen = 0;
960 }
961
962 /*!
963  * Open data-, metadata(header)- or ressource fork
964  *
965  * You must call ad_init() before ad_open, usually you'll just call it like this: \n
966  * @code
967  *      struct adoube ad;
968  *      ad_init(&ad, vol->v_adouble, vol->v_ad_options);
969  * @endcode
970  *
971  * @param path    Path to file or directory
972  *
973  * @param adflags ADFLAGS_DF:        open data fork \n
974  *                ADFLAGS_RF:        open ressource fork \n
975  *                ADFLAGS_HF:        open header (metadata) file \n
976  *                ADFLAGS_NOHF:      it's not an error if header file couldn't be created \n
977  *                ADFLAGS_DIR:       if path is a directory you MUST or ADFLAGS_DIR to adflags \n
978  *                ADFLAGS_NOADOUBLE: dont create adouble files if not necessary \n
979  *                ADFLAGS_RDONLY:    open read only \n
980  *                ADFLAGS_OPENFORKS: check for open forks from other processes
981  *
982  * @param oflags  flags passed through to open syscall: \n
983  *                O_RDONLY: *** FIXME *** \n
984  *                O_RDWR: *** FIXME *** \n
985  *                O_CREAT: create fork \n
986  *                O_EXCL: fail if exists with O_CREAT
987  *
988  * @param mode    passed to open with O_CREAT
989  * @param ad      pointer to struct adouble
990  *
991  * @returns 0 on success
992  *
993  * @note It's not possible to open the header file O_RDONLY -- the read
994  *       will fail and return an error. this refcounts things now.\n
995  *       metadata(ressource)-fork only gets created with O_CREAT.
996  */
997 int ad_open(const char *path, int adflags, int oflags, int mode, struct adouble  *ad)
998 {
999     if (ad->ad_inited != AD_INITED) {
1000         ad->ad_inited = AD_INITED;
1001         ad->ad_refcount = 1;
1002         ad->ad_open_forks = 0;
1003         ad->ad_adflags = adflags;
1004         ad->ad_resource_fork.adf_refcount = 0;
1005         ad->ad_data_fork.adf_refcount = 0;
1006         ad->ad_data_fork.adf_syml = 0;
1007     } else {
1008         ad->ad_open_forks = ((ad->ad_data_fork.adf_refcount > 0) ? ATTRBIT_DOPEN : 0);
1009         /* XXX not true if we have a meta data fork ? */
1010         if ((ad->ad_resource_fork.adf_refcount > ad->ad_data_fork.adf_refcount))
1011             ad->ad_open_forks |= ATTRBIT_ROPEN;
1012     }
1013
1014     if ((adflags & ADFLAGS_DF)) {
1015         if (ad_open_df(path, adflags, oflags, mode, ad) != 0)
1016             return -1;
1017     }
1018
1019     if ((adflags & ADFLAGS_HF)) {
1020         if (ad_open_hf(path, adflags, oflags, mode, ad) != 0)
1021             return -1;
1022     }
1023
1024 #if 0
1025     if ((adflags & ADFLAGS_RF)) {
1026         if (ad_open_rf(path, adflags, oflags, mode, ad) != 0)
1027             return -1;
1028     }
1029 #endif
1030
1031     return 0;
1032 }
1033
1034 /*!
1035  * @brief open metadata, possibly as root
1036  *
1037  * Return only metadata but try very hard ie at first try as user, then try as root.
1038  *
1039  * @param name  name of file/dir
1040  * @param flags ADFLAGS_DIR: name is a directory \n
1041  *              ADFLAGS_CREATE: force creation of header file, but only as user, not as root\n
1042  *              ADFLAGS_OPENFORKS: test if name is open by another afpd process
1043  *
1044  * @param adp   pointer to struct adouble
1045  *
1046  * @note caller MUST pass ADFLAGS_DIR for directories. Whether ADFLAGS_CREATE really creates
1047  *       a adouble file depends on various other volume options, eg. ADVOL_CACHE
1048  */
1049 int ad_metadata(const char *name, int flags, struct adouble *adp)
1050 {
1051     uid_t uid;
1052     int   ret, err, dir;
1053     int   create = O_RDONLY;
1054
1055     dir = flags & ADFLAGS_DIR;
1056
1057     /* Check if we shall call ad_open with O_CREAT */
1058     if ( (adp->ad_options & ADVOL_CACHE)
1059          && ! (adp->ad_options & ADVOL_NOADOUBLE)
1060          && (flags & ADFLAGS_CREATE) ) {
1061         create = O_CREAT | O_RDWR;
1062     }
1063     if ((ret = ad_open(name, ADFLAGS_HF | dir, create, 0666, adp)) < 0 && errno == EACCES) {
1064         uid = geteuid();
1065         if (seteuid(0)) {
1066             LOG(log_error, logtype_default, "ad_metadata(%s): seteuid failed %s", name, strerror(errno));
1067             errno = EACCES;
1068             return -1;
1069         }
1070         /* we are root open read only */
1071         ret = ad_open(name, ADFLAGS_HF|ADFLAGS_RDONLY| dir, O_RDONLY, 0, adp);
1072         err = errno;
1073         if ( seteuid(uid) < 0) {
1074             LOG(log_error, logtype_default, "ad_metadata: can't seteuid back");
1075             exit(EXITERR_SYS);
1076         }
1077         errno = err;
1078     }
1079
1080     if (!ret && (ADFLAGS_OPENFORKS & flags)) {
1081         /*
1082           we need to check if the file is open by another process.
1083           it's slow so we only do it if we have to:
1084           - it's requested.
1085           - we don't already have the answer!
1086         */
1087         adp->ad_open_forks |= ad_openforks(adp, adp->ad_open_forks);
1088     }
1089     return ret;
1090 }
1091
1092 /*
1093  * @brief openat like wrapper for ad_metadata
1094  */
1095 int ad_metadataat(int dirfd, const char *name, int flags, struct adouble *adp)
1096 {
1097     int ret = 0;
1098     int cwdfd = -1;
1099
1100     if (dirfd != -1) {
1101         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1102             ret = -1;
1103             goto exit;
1104         }
1105     }
1106
1107     if (ad_metadata(name, flags, adp) < 0) {
1108         ret = -1;
1109         goto exit;
1110     }
1111
1112     if (dirfd != -1) {
1113         if (fchdir(cwdfd) != 0) {
1114             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1115             exit(EXITERR_SYS);
1116         }
1117     }
1118
1119 exit:
1120     if (cwdfd != -1)
1121         close(cwdfd);
1122
1123     return ret;
1124
1125 }
1126
1127 int ad_refresh(struct adouble *ad)
1128 {
1129
1130     if (ad_meta_fileno(ad) == -1)
1131         return -1;
1132
1133     return ad->ad_ops->ad_header_read(ad, NULL);
1134 }
1135
1136 int ad_openat(int dirfd,  /* dir fd openat like */
1137               const char *path,
1138               int adflags,
1139               int oflags,
1140               int mode,
1141               struct adouble  *ad)
1142 {
1143     int ret = 0;
1144     int cwdfd = -1;
1145
1146     if (dirfd != -1) {
1147         if ((cwdfd = open(".", O_RDONLY) == -1) || (fchdir(dirfd) != 0)) {
1148             ret = -1;
1149             goto exit;
1150         }
1151     }
1152
1153     if (ad_open(path, adflags, oflags, mode, ad) < 0) {
1154         ret = -1;
1155         goto exit;
1156     }
1157
1158     if (dirfd != -1) {
1159         if (fchdir(cwdfd) != 0) {
1160             LOG(log_error, logtype_afpd, "ad_openat: cant chdir back, exiting");
1161             exit(EXITERR_SYS);
1162         }
1163     }
1164
1165 exit:
1166     if (cwdfd != -1)
1167         close(cwdfd);
1168
1169     return ret;
1170 }