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