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