]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
Don't implement ad_hf_mode in header file, but always use the function in
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * $Id: ad_open.c,v 1.31 2003-06-06 20:46:38 srittau Exp $
3  *
4  * Copyright (c) 1999 Adrian Sun (asun@u.washington.edu)
5  * Copyright (c) 1990,1991 Regents of The University of Michigan.
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  * NOTE: I don't use inline because a good compiler should be
27  * able to optimize all the static below. Didier
28  */
29
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif /* HAVE_CONFIG_H */
33
34 #include <string.h>
35 #ifdef HAVE_FCNTL_H
36 #include <fcntl.h>
37 #endif /* HAVE_FCNTL_H */
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif /* HAVE_UNISTD_H */
41 #include <errno.h>
42 #include <atalk/logger.h>
43
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/param.h>
48 #include <sys/mman.h>
49
50 #include <netatalk/endian.h>
51 #include <atalk/adouble.h>
52
53 #include "ad_private.h"
54
55 #ifndef MAX
56 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
57 #endif /* ! MAX */
58
59 /*
60  * AppleDouble entry default offsets.
61  * The layout looks like this:
62  *
63  * this is the v1 layout:
64  *        255     200             16      32              N
65  *      |  NAME |    COMMENT    | FILEI |    FINDERI    | RFORK |
66  *
67  * we need to change it to look like this:
68  *
69  * v2 layout:
70  * field       length (in bytes)
71  * NAME        255
72  * COMMENT     200
73  * FILEDATESI  16     replaces FILEI
74  * FINDERI     32  
75  * DID          4     new
76  * AFPFILEI     4     new
77  * SHORTNAME   12     8.3 new
78  * RFORK        N
79  * 
80  * so, all we need to do is replace FILEI with FILEDATESI, move RFORK,
81  * and add in the new fields.
82  *
83  * NOTE: the HFS module will need similar modifications to interact with
84  * afpd correctly.
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 #define ADEID_NUM_V1         5
101 #define ADEDOFF_NAME_V1      (AD_HEADER_LEN + ADEID_NUM_V1*AD_ENTRY_LEN)
102 #define ADEDOFF_COMMENT_V1   (ADEDOFF_NAME_V1 + ADEDLEN_NAME)
103 #define ADEDOFF_FILEI        (ADEDOFF_COMMENT_V1 + ADEDLEN_COMMENT)
104 #define ADEDOFF_FINDERI_V1   (ADEDOFF_FILEI + ADEDLEN_FILEI)
105 #define ADEDOFF_RFORK_V1     (ADEDOFF_FINDERI_V1 + ADEDLEN_FINDERI)
106
107 /* i stick things in a slightly different order than their eid order in 
108  * case i ever want to separate RootInfo behaviour from the rest of the 
109  * stuff. */
110 #define ADEID_NUM_V2         9
111 #define ADEDOFF_NAME_V2      (AD_HEADER_LEN + ADEID_NUM_V2*AD_ENTRY_LEN)
112 #define ADEDOFF_COMMENT_V2   (ADEDOFF_NAME_V2 + ADEDLEN_NAME)
113 #define ADEDOFF_FILEDATESI   (ADEDOFF_COMMENT_V2 + ADEDLEN_COMMENT)
114 #define ADEDOFF_FINDERI_V2   (ADEDOFF_FILEDATESI + ADEDLEN_FILEDATESI)
115 #define ADEDOFF_DID          (ADEDOFF_FINDERI_V2 + ADEDLEN_FINDERI)
116 #define ADEDOFF_AFPFILEI     (ADEDOFF_DID + ADEDLEN_DID)
117 #define ADEDOFF_SHORTNAME    (ADEDOFF_AFPFILEI + ADEDLEN_AFPFILEI)
118 #define ADEDOFF_PRODOSFILEI  (ADEDOFF_SHORTNAME + ADEDLEN_SHORTNAME)
119 #define ADEDOFF_RFORK_V2     (ADEDOFF_PRODOSFILEI + ADEDLEN_PRODOSFILEI)
120
121
122
123 /* we keep local copies of a bunch of stuff so that we can initialize things 
124  * correctly. */
125
126 /* Bits in the finderinfo data. 
127  * see etc/afpd/{directory.c,file.c} for the finderinfo structure
128  * layout. */
129 #define FINDERINFO_CUSTOMICON 0x4
130 #define FINDERINFO_CLOSEDVIEW 0x100
131
132 /* offsets in finderinfo */
133 #define FINDERINFO_FRTYPEOFF   0
134 #define FINDERINFO_FRCREATOFF  4
135 #define FINDERINFO_FRFLAGOFF   8
136 #define FINDERINFO_FRVIEWOFF  14
137
138 /* invisible bit for dot files */
139 #define ATTRBIT_INVISIBLE     (1 << 0)
140 #define FINDERINFO_INVISIBLE  (1 << 14)
141
142 /* this is to prevent changing timezones from causing problems with
143    localtime volumes. the screw-up is 30 years. we use a delta of 5
144    years.  */
145 #define TIMEWARP_DELTA 157680000
146
147
148 struct entry {
149   u_int32_t id, offset, len;
150 };
151
152 #if AD_VERSION == AD_VERSION1 
153 static const struct entry entry_order[] = {
154   {ADEID_NAME, ADEDOFF_NAME_V1, ADEDLEN_INIT},
155   {ADEID_COMMENT, ADEDOFF_COMMENT_V1, ADEDLEN_INIT},
156   {ADEID_FILEI, ADEDOFF_FILEI, ADEDLEN_FILEI},
157   {ADEID_FINDERI, ADEDOFF_FINDERI_V1, ADEDLEN_FINDERI},
158   {ADEID_RFORK, ADEDOFF_RFORK_V1, ADEDLEN_INIT},
159   {0, 0, 0}
160 };
161 #else /* AD_VERSION == AD_VERSION2 */
162 static const struct entry entry_order[] = {
163   {ADEID_NAME, ADEDOFF_NAME_V2, ADEDLEN_INIT},
164   {ADEID_COMMENT, ADEDOFF_COMMENT_V2, ADEDLEN_INIT},
165   {ADEID_FILEDATESI, ADEDOFF_FILEDATESI, ADEDLEN_FILEDATESI},
166   {ADEID_FINDERI, ADEDOFF_FINDERI_V2, ADEDLEN_FINDERI},
167   {ADEID_DID, ADEDOFF_DID, ADEDLEN_DID},
168   {ADEID_AFPFILEI, ADEDOFF_AFPFILEI, ADEDLEN_AFPFILEI},
169   {ADEID_SHORTNAME, ADEDOFF_SHORTNAME, ADEDLEN_INIT},
170   {ADEID_PRODOSFILEI, ADEDOFF_PRODOSFILEI, ADEDLEN_PRODOSFILEI},
171   {ADEID_RFORK, ADEDOFF_RFORK_V2, ADEDLEN_INIT},
172   {0, 0, 0}
173 };
174 #endif /* AD_VERSION == AD_VERSION2 */
175
176 #if AD_VERSION == AD_VERSION2
177
178
179 static __inline__ int ad_v1tov2(struct adouble *ad, const char *path)
180 {
181   struct stat st;
182   u_int16_t attr;
183   char *buf;
184   int fd, off;
185   
186   /* check to see if we should convert this header. */
187   if (!path || (ad->ad_version != AD_VERSION1))
188     return 0;
189
190   /* convert from v1 to v2. what does this mean?
191    *  1) change FILEI into FILEDATESI
192    *  2) create space for SHORTNAME, AFPFILEI, DID, and PRODOSI
193    *  3) move FILEI attributes into AFPFILEI
194    *  4) initialize ACCESS field of FILEDATESI.
195    *
196    *  so, we need 4*12 (entry ids) + 12 (shortname) + 4 (afpfilei) +
197    *  4 (did) + 8 (prodosi) = 76 more bytes.  */
198   
199 #define SHIFTDATA (AD_DATASZ2 - AD_DATASZ1)
200
201   /* bail if we can't get a lock */
202   if (ad_tmplock(ad, ADEID_RFORK, ADLOCK_WR, 0, 0, 0) < 0) 
203     goto bail_err;
204   
205   if ((fd = open(path, O_RDWR)) < 0) 
206     goto bail_lock;
207   
208   if (fstat(fd, &st) ||
209       ftruncate(fd, st.st_size + SHIFTDATA) < 0) {
210     goto bail_open;
211   }
212   
213   /* last place for failure. */
214   if ((void *) (buf = (char *) 
215                 mmap(NULL, st.st_size + SHIFTDATA,
216                      PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == 
217           MAP_FAILED) {
218     goto bail_truncate;
219   }
220   
221   off = ad->ad_eid[ADEID_RFORK].ade_off;
222
223   /* move the RFORK. this assumes that the RFORK is at the end */
224   memmove(buf + off + SHIFTDATA, buf + off, 
225           ad->ad_eid[ADEID_RFORK].ade_len);
226   
227   munmap(buf, st.st_size + SHIFTDATA);
228   close(fd);
229
230   /* now, fix up our copy of the header */
231   memset(ad->ad_filler, 0, sizeof(ad->ad_filler));
232   
233   /* replace FILEI with FILEDATESI */
234   ad_getattr(ad, &attr);
235   ad->ad_eid[ADEID_FILEDATESI].ade_off = ADEDOFF_FILEDATESI;
236   ad->ad_eid[ADEID_FILEDATESI].ade_len = ADEDLEN_FILEDATESI;
237   ad->ad_eid[ADEID_FILEI].ade_off = 0;
238   ad->ad_eid[ADEID_FILEI].ade_len = 0;
239   
240   /* add in the new entries */
241   ad->ad_eid[ADEID_DID].ade_off = ADEDOFF_DID;
242   ad->ad_eid[ADEID_DID].ade_len = ADEDLEN_DID;
243   ad->ad_eid[ADEID_AFPFILEI].ade_off = ADEDOFF_AFPFILEI;
244   ad->ad_eid[ADEID_AFPFILEI].ade_len = ADEDLEN_AFPFILEI;
245   ad->ad_eid[ADEID_SHORTNAME].ade_off = ADEDOFF_SHORTNAME;
246   ad->ad_eid[ADEID_SHORTNAME].ade_len = ADEDLEN_INIT;
247   ad->ad_eid[ADEID_PRODOSFILEI].ade_off = ADEDOFF_PRODOSFILEI;
248   ad->ad_eid[ADEID_PRODOSFILEI].ade_len = ADEDLEN_PRODOSFILEI;
249   
250   /* shift the old entries (NAME, COMMENT, FINDERI, RFORK) */
251   ad->ad_eid[ADEID_NAME].ade_off = ADEDOFF_NAME_V2;
252   ad->ad_eid[ADEID_COMMENT].ade_off = ADEDOFF_COMMENT_V2;
253   ad->ad_eid[ADEID_FINDERI].ade_off = ADEDOFF_FINDERI_V2;
254   ad->ad_eid[ADEID_RFORK].ade_off = ADEDOFF_RFORK_V2;
255   
256   /* switch to v2 */
257   ad->ad_version = AD_VERSION2;
258   
259   /* move our data buffer to make space for the new entries. */
260   memmove(ad->ad_data + ADEDOFF_NAME_V2, ad->ad_data + ADEDOFF_NAME_V1,
261           ADEDOFF_RFORK_V1 - ADEDOFF_NAME_V1);
262   
263   /* now, fill in the space with appropriate stuff. we're
264      operating as a v2 file now. */
265   ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
266   memset(ad_entry(ad, ADEID_DID), 0, ADEDLEN_DID);
267   memset(ad_entry(ad, ADEID_AFPFILEI), 0, ADEDLEN_AFPFILEI);
268   ad_setattr(ad, attr);
269   memset(ad_entry(ad, ADEID_SHORTNAME), 0, ADEDLEN_SHORTNAME);
270   memset(ad_entry(ad, ADEID_PRODOSFILEI), 0, ADEDLEN_PRODOSFILEI);
271   
272   /* rebuild the header and cleanup */
273   ad_flush(ad, ADFLAGS_HF );
274   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
275
276   return 0;
277   
278 bail_truncate:
279   ftruncate(fd, st.st_size);
280 bail_open:
281   close(fd);
282 bail_lock:
283   ad_tmplock(ad, ADEID_RFORK, ADLOCK_CLR, 0, 0, 0);
284 bail_err:
285   return -1;
286 }
287 #endif /* AD_VERSION == AD_VERSION2 */
288
289 mode_t ad_hf_mode (mode_t mode)
290 {
291     /* fnctl lock need write access */
292     if ((mode & S_IRUSR))
293         mode |= S_IWUSR;
294     if ((mode & S_IRGRP))
295         mode |= S_IWGRP;
296     if ((mode & S_IROTH))
297         mode |= S_IWOTH;
298     /* if write mode set add read mode */
299     if ((mode & S_IWUSR))
300         mode |= S_IRUSR;
301     if ((mode & S_IWGRP))
302         mode |= S_IRGRP;
303     if ((mode & S_IWOTH))
304         mode |= S_IROTH;
305
306     return mode;
307 }
308
309 /* ------------------------------------- 
310   read in the entries 
311 */
312 static void parse_entries(struct adouble *ad, char *buf,
313                                     u_int16_t nentries)
314 {
315     u_int32_t   eid, len, off;
316     int         warning = 0;
317
318     /* now, read in the entry bits */
319     for (; nentries > 0; nentries-- ) {
320         memcpy(&eid, buf, sizeof( eid ));
321         eid = ntohl( eid );
322         buf += sizeof( eid );
323         memcpy(&off, buf, sizeof( off ));
324         off = ntohl( off );
325         buf += sizeof( off );
326         memcpy(&len, buf, sizeof( len ));
327         len = ntohl( len );
328         buf += sizeof( len );
329
330         if ( 0 < eid && eid < ADEID_MAX ) {
331             ad->ad_eid[ eid ].ade_off = off;
332             ad->ad_eid[ eid ].ade_len = len;
333         } else if (!warning) {
334             warning = 1;
335             LOG(log_debug, logtype_default, "ad_refresh: nentries %hd  eid %d\n",
336                     nentries, eid );
337         }
338     }
339 }
340
341
342 /* this reads enough of the header so that we can figure out all of
343  * the entry lengths and offsets. once that's done, we just read/mmap
344  * the rest of the header in.
345  *
346  * NOTE: we're assuming that the resource fork is kept at the end of
347  *       the file. also, mmapping won't work for the hfs fs until it
348  *       understands how to mmap header files. */
349 static int ad_header_read(struct adouble *ad, struct stat *hst)
350 {
351     char                *buf = ad->ad_data;
352     u_int16_t           nentries;
353     int                 len;
354     ssize_t             header_len;
355     static int          warning = 0;
356     struct stat         st;
357
358     /* read the header */
359     if ((header_len = adf_pread( &ad->ad_hf, buf, sizeof(ad->ad_data), 0)) < 0) {
360         return -1;
361     }
362     if (header_len < AD_HEADER_LEN) {
363         errno = EIO;
364         return -1;
365     }
366
367     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
368     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
369
370     /* tag broken v1 headers. just assume they're all right. 
371      * we detect two cases: null magic/version
372      *                      byte swapped magic/version
373      * XXX: in the future, you'll need the v1compat flag. 
374      * (ad->ad_flags & ADFLAGS_V1COMPAT) */
375     if (!ad->ad_magic && !ad->ad_version) {
376       if (!warning) {
377         LOG(log_debug, logtype_default, "notice: fixing up null v1 magic/version.");
378         warning++;
379       }
380       ad->ad_magic = AD_MAGIC;
381       ad->ad_version = AD_VERSION1;
382
383     } else if (ad->ad_magic == AD_MAGIC && ad->ad_version == AD_VERSION1) {
384       if (!warning) {
385         LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
386         warning++;
387       }
388
389     } else {
390       ad->ad_magic = ntohl( ad->ad_magic );
391       ad->ad_version = ntohl( ad->ad_version );
392     }
393
394     if ((ad->ad_magic != AD_MAGIC) || ((ad->ad_version != AD_VERSION1)
395 #if AD_VERSION == AD_VERSION2
396                                        && (ad->ad_version != AD_VERSION2)
397 #endif /* AD_VERSION == AD_VERSION2 */
398                                        )) {
399       errno = EIO;
400       LOG(log_debug, logtype_default, "ad_open: can't parse AppleDouble header.");
401       return -1;
402     }
403
404     memcpy(ad->ad_filler, buf + ADEDOFF_FILLER, sizeof( ad->ad_filler ));
405     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
406     nentries = ntohs( nentries );
407
408     /* read in all the entry headers. if we have more than the 
409      * maximum, just hope that the rfork is specified early on. */
410     len = nentries*AD_ENTRY_LEN;
411
412     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
413       len = sizeof(ad->ad_data) - AD_HEADER_LEN;
414
415     buf += AD_HEADER_LEN;
416     if (len > header_len - AD_HEADER_LEN) {
417         errno = EIO;
418         LOG(log_debug, logtype_default, "ad_header_read: can't read entry info.");
419         return -1;
420     }
421
422     /* figure out all of the entry offsets and lengths. if we aren't
423      * able to read a resource fork entry, bail. */
424     nentries = len / AD_ENTRY_LEN;
425     parse_entries(ad, buf, nentries);
426     if (!ad_getentryoff(ad, ADEID_RFORK)
427         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
428         ) {
429       LOG(log_debug, logtype_default, "ad_header_read: problem with rfork entry offset."); 
430       return -1;
431     }
432
433     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
434         errno = EIO;
435         LOG(log_debug, logtype_default, "ad_header_read: can't read in entries.");
436         return -1;
437     }
438     
439     if (hst == NULL) {
440         hst = &st;
441         if (fstat(ad->ad_hf.adf_fd, &st) < 0) {
442             return 1; /* fail silently */
443          }
444     }
445     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
446
447     /* fix up broken dates */
448     if (ad->ad_version == AD_VERSION1) {
449       u_int32_t aint;
450       
451       /* check to see if the ad date is wrong. just see if we have
452       * a modification date in the future. */
453       if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
454           (aint > TIMEWARP_DELTA + hst->st_mtime)) {
455         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
456         ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
457         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
458         ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
459         ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
460       }
461     }
462
463     return 0;
464 }
465
466
467 /*
468  * Put the .AppleDouble where it needs to be:
469  *
470  *          /   a/.AppleDouble/b
471  *      a/b
472  *          \   b/.AppleDouble/.Parent
473  */
474 char *
475 ad_path( path, adflags )
476     const char  *path;
477     int         adflags;
478 {
479     static char pathbuf[ MAXPATHLEN + 1];
480     char        c, *slash, buf[MAXPATHLEN + 1];
481
482     strncpy(buf, path, MAXPATHLEN);
483     if ( adflags & ADFLAGS_DIR ) {
484         strncpy( pathbuf, buf, MAXPATHLEN );
485         if ( *buf != '\0' ) {
486             strcat( pathbuf, "/" );
487         }
488         slash = ".Parent";
489     } else {
490         if (NULL != ( slash = strrchr( buf, '/' )) ) {
491             c = *++slash;
492             *slash = '\0';
493             strncpy( pathbuf, buf, MAXPATHLEN);
494             *slash = c;
495         } else {
496             pathbuf[ 0 ] = '\0';
497             slash = buf;
498         }
499     }
500     strncat( pathbuf, ".AppleDouble/", MAXPATHLEN - strlen(pathbuf));
501     strncat( pathbuf, slash, MAXPATHLEN - strlen(pathbuf));
502
503     return( pathbuf );
504 }
505
506 /*
507  * Support inherited protection modes for AppleDouble files.  The supplied
508  * mode is ANDed with the parent directory's mask value in lieu of "umask",
509  * and that value is returned.
510  */
511
512 #define DEFMASK 07700   /* be conservative */
513
514 char 
515 *ad_dir(path)
516     const char          *path;
517 {
518     static char         modebuf[ MAXPATHLEN + 1];
519     char                *slash;
520
521     if ( strlen( path ) >= MAXPATHLEN ) {
522         errno = ENAMETOOLONG;
523         return NULL;  /* can't do it */
524     }
525
526     /*
527      * For a path with directories in it, remove the final component
528      * (path or subdirectory name) to get the name we want to stat.
529      * For a path which is just a filename, use "." instead.
530      */
531     strcpy( modebuf, path );
532     if (NULL != ( slash = strrchr( modebuf, '/' )) ) {
533         *slash = '\0';          /* remove pathname component */
534     } else {
535         modebuf[0] = '.';       /* use current directory */
536         modebuf[1] = '\0';
537     }
538     return modebuf;
539 }
540
541 /* ---------------- */
542 static uid_t default_uid = -1;
543
544 int ad_setfuid(const uid_t id)
545 {
546     default_uid = id;
547     return 0;
548 }
549
550 /* ---------------- */
551 uid_t ad_getfuid(void) 
552 {
553     return default_uid;
554 }
555
556 /* ---------------- 
557    return inode of path parent directory
558 */
559 static int ad_stat(const char *path, struct stat *stbuf)
560 {
561     char                *p;
562
563     p = ad_dir(path);
564     if (!p) {
565         return -1;
566     }
567
568     return stat( p, stbuf );
569 }
570
571 /* ---------------- 
572    if we are root change path user/ group
573    It can be a native function for BSD cf. FAQ.Q10
574    path:  pathname to chown 
575    stbuf: parent directory inode
576    
577    use fstat and fchown or lchown with linux?
578 */
579 #define EMULATE_SUIDDIR
580  
581 static int ad_chown(const char *path, struct stat *stbuf)
582 {
583 int ret = 0;
584 #ifdef EMULATE_SUIDDIR
585 uid_t id;
586
587     if (default_uid != -1) {  
588         /* we are root (admin) */
589         id = (default_uid)?default_uid:stbuf->st_uid;
590         ret = chown( path, id, stbuf->st_gid );
591     }
592 #endif    
593     return ret;
594 }
595
596 /* ---------------- 
597    return access right and inode of path parent directory
598 */
599 static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
600 {
601     if (*mode == 0) {
602        return -1;
603     }
604     if (ad_stat(path, stbuf) != 0) {
605         *mode &= DEFMASK;
606         return -1;
607     }
608     *mode &= stbuf->st_mode;
609     return 0;    
610 }
611
612 /* ---------------- 
613    return access right of path parent directory
614 */
615 int
616 ad_mode( path, mode )
617     const char          *path;
618     int                 mode;
619 {
620     struct stat         stbuf;
621     ad_mode_st(path, &mode, &stbuf);
622     return mode;
623 }
624
625 /*
626  * Use mkdir() with mode bits taken from ad_mode().
627  */
628 int
629 ad_mkdir( path, mode )
630     const char          *path;
631     int                 mode;
632 {
633 int ret;
634 int st_invalid;
635 struct stat stbuf;
636
637 #ifdef DEBUG
638     LOG(log_info, logtype_default, "ad_mkdir: Creating directory with mode %d", mode);
639 #endif /* DEBUG */
640
641     st_invalid = ad_mode_st(path, &mode, &stbuf);
642     ret = mkdir( path, mode );
643     if (ret || st_invalid)
644         return ret;
645     ad_chown(path, &stbuf);
646
647     return ret;    
648 }
649
650 /* ----------------- */
651 static int ad_error(struct adouble *ad, int adflags)
652 {
653     if ((adflags & ADFLAGS_NOHF)) {
654         /* FIXME double check : set header offset ?*/
655         return 0;
656     }
657     if ((adflags & ADFLAGS_DF)) {
658         ad_close( ad, ADFLAGS_DF );
659     }
660     return -1 ;
661 }
662
663 static int new_rfork(const char *path, struct adouble *ad, int adflags);
664
665 #ifdef  HAVE_PREAD
666 #define AD_SET(a) 
667 #else 
668 #define AD_SET(a) a = 0
669 #endif
670 /*
671  * It's not possible to open the header file O_RDONLY -- the read
672  * will fail and return an error. this refcounts things now. 
673  */
674 int ad_open( path, adflags, oflags, mode, ad )
675     const char          *path;
676     int                 adflags, oflags, mode;
677     struct adouble      *ad;
678 {
679     struct stat         st;
680     char                *slash, *ad_p;
681     int                 hoflags, admode;
682     int                 st_invalid;
683     int                 open_df = 0;
684     
685     if (ad->ad_inited != AD_INITED) {
686         ad_dfileno(ad) = -1;
687         ad_hfileno(ad) = -1;
688         adf_lock_init(&ad->ad_df);
689         adf_lock_init(&ad->ad_hf);
690         ad->ad_inited = AD_INITED;
691         ad->ad_refcount = 1;
692     }
693
694     if ((adflags & ADFLAGS_DF)) { 
695         if (ad_dfileno(ad) == -1) {
696           hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
697           admode = mode;
698           st_invalid = ad_mode_st(path, &admode, &st);
699           ad->ad_df.adf_fd =open( path, hoflags, admode );
700           if (ad->ad_df.adf_fd < 0 ) {
701              if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
702                 hoflags = oflags;
703                 ad->ad_df.adf_fd =open( path, hoflags, admode );
704              }
705           }
706           if ( ad->ad_df.adf_fd < 0)
707                 return -1;
708
709           AD_SET(ad->ad_df.adf_off);
710           ad->ad_df.adf_flags = hoflags;
711           if ((oflags & O_CREAT) && !st_invalid) {
712               /* just created, set owner if admin (root) */
713               ad_chown(path, &st);
714           }
715         } 
716         else {
717             /* the file is already open... but */
718             if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
719                 !(ad->ad_df.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
720             {
721                  errno = EACCES;
722                  return -1;
723             }
724             /* FIXME 
725              * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
726              * already open. Should we check for it? ie
727              * O_EXCL --> error 
728              * O_TRUNC --> truncate the fork.
729              * idem for ressource fork.
730              */
731         }
732         open_df = ADFLAGS_DF;
733         ad->ad_df.adf_refcount++;
734     }
735
736     if (!(adflags & ADFLAGS_HF)) 
737         return 0;
738         
739     if (ad_hfileno(ad) != -1) { /* the file is already open */
740         if ((oflags & ( O_RDWR | O_WRONLY)) &&             
741                 !(ad->ad_hf.adf_flags & ( O_RDWR | O_WRONLY))) {
742             if (open_df) {
743                 /* don't call with ADFLAGS_HF because we didn't open ressource fork */
744                 ad_close( ad, open_df );
745             }
746             errno = EACCES;
747             return -1;
748         }
749         ad_refresh(ad);
750         ad->ad_hf.adf_refcount++;
751         return 0;
752     }
753
754     ad_p = ad_path( path, adflags );
755
756     hoflags = oflags & ~O_CREAT;
757     hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
758     ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
759     if (ad->ad_hf.adf_fd < 0 ) {
760         if ((errno == EACCES || errno == EROFS) && !(oflags & O_RDWR)) {
761             hoflags = oflags & ~O_CREAT;
762             ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
763         }    
764     }
765
766     if ( ad->ad_hf.adf_fd < 0 ) { 
767         if (errno == ENOENT && (oflags & O_CREAT) ) {
768             /*
769              * We're expecting to create a new adouble header file,
770              * here.
771              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
772              */
773             admode = mode;
774             st_invalid = ad_mode_st(ad_p, &admode, &st);
775             admode = ad_hf_mode(admode); 
776             errno = 0;
777             ad->ad_hf.adf_fd = open( ad_p, oflags,admode );
778             if ( ad->ad_hf.adf_fd < 0 ) {
779                 /*
780                  * Probably .AppleDouble doesn't exist, try to
781                  * mkdir it.
782                  */
783                 if (errno == ENOENT && (adflags & ADFLAGS_NOADOUBLE) == 0) {
784                     if (NULL == ( slash = strrchr( ad_p, '/' )) ) {
785                         return ad_error(ad, adflags);
786                     }
787                     *slash = '\0';
788                     errno = 0;
789                     if ( ad_mkdir( ad_p, 0777 ) < 0 ) {
790                         return ad_error(ad, adflags);
791                     }
792                     *slash = '/';
793                     admode = mode;
794                     st_invalid = ad_mode_st(ad_p, &admode, &st);
795                     admode = ad_hf_mode(admode); 
796                     ad->ad_hf.adf_fd = open( ad_p, oflags, admode);
797                     if ( ad->ad_hf.adf_fd < 0 ) {
798                         return ad_error(ad, adflags);
799                     }
800                 } else {
801                      return ad_error(ad, adflags);
802                 }
803             }
804             ad->ad_hf.adf_flags = oflags;
805             /* just created, set owner if admin owner (root) */
806             if (!st_invalid) {
807                 ad_chown(path, &st);
808             }
809         }
810         else {
811             return ad_error(ad, adflags);
812         }
813     } else if (fstat(ad->ad_hf.adf_fd, &st) == 0 && st.st_size == 0) {
814         /* for 0 length files, treat them as new. */
815         ad->ad_hf.adf_flags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR | O_TRUNC;
816     } else {
817         ad->ad_hf.adf_flags = hoflags;
818     }
819     AD_SET(ad->ad_hf.adf_off);
820           
821     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
822     ad->ad_hf.adf_refcount++;
823     if ((ad->ad_hf.adf_flags & ( O_TRUNC | O_CREAT ))) {
824         /*
825          * This is a new adouble header file. Initialize the structure,
826          * instead of reading it.
827         */
828         if (new_rfork(path, ad, adflags) < 0) {
829             /* the file is already deleted, perm, whatever, so return an error*/
830             ad_close(ad, adflags);
831             return -1;
832         }
833     } else {
834             /* Read the adouble header in and parse it.*/
835         if ((ad_header_read( ad , &st) < 0)
836 #if AD_VERSION == AD_VERSION2
837                 || (ad_v1tov2(ad, ad_p) < 0)
838 #endif /* AD_VERSION == AD_VERSION2 */
839         ) {
840             ad_close( ad, adflags );
841             return( -1 );
842         }
843     }
844     return 0 ;
845 }
846
847 /* ----------------------------------- */
848 static int new_rfork(const char *path, struct adouble *ad, int adflags)
849 {
850 #if 0
851     struct timeval      tv;
852 #endif    
853     const struct entry  *eid;
854     u_int16_t           ashort;
855     struct stat         st;
856
857     ad->ad_magic = AD_MAGIC;
858     ad->ad_version = AD_VERSION;
859
860     memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
861     memset(ad->ad_data, 0, sizeof(ad->ad_data));
862
863     eid = entry_order;
864     while (eid->id) {
865         ad->ad_eid[eid->id].ade_off = eid->offset;
866         ad->ad_eid[eid->id].ade_len = eid->len;
867         eid++;
868     }
869             
870     /* put something sane in the directory finderinfo */
871     if (adflags & ADFLAGS_DIR) {
872         /* set default view */
873         ashort = htons(FINDERINFO_CLOSEDVIEW);
874         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, 
875                      &ashort, sizeof(ashort));
876     } else {
877         /* set default creator/type fields */
878         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"TEXT", 4);
879         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"UNIX", 4);
880     }
881
882     /* make things invisible */
883     if ((*path == '.') && strcmp(path, ".") && strcmp(path, "..")) {
884         ashort = htons(ATTRBIT_INVISIBLE);
885         ad_setattr(ad, ashort);
886         ashort = htons(FINDERINFO_INVISIBLE);
887         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,
888                      &ashort, sizeof(ashort));
889     }
890
891 #if 0
892     if (gettimeofday(&tv, NULL) < 0) {
893         return -1;
894     } 
895 #endif
896     
897     if (stat(path, &st) < 0) {
898         return -1;
899     }
900             
901     /* put something sane in the date fields */
902     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
903     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
904     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
905     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
906     return 0;
907 }
908
909 /* to do this with mmap, we need the hfs fs to understand how to mmap
910    header files. */
911 int ad_refresh(struct adouble *ad)
912 {
913
914   if (ad->ad_hf.adf_fd < -1)
915     return -1;
916
917   return ad_header_read(ad, NULL);
918 }