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