]> arthur.barton.de Git - netatalk.git/blob - libatalk/adouble/ad_open.c
4d7781719a70f73ca1a0af98d81fc8fc61e18f00
[netatalk.git] / libatalk / adouble / ad_open.c
1 /*
2  * $Id: ad_open.c,v 1.29 2003-03-09 19:55:35 didg 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 #ifdef ATACC
290 mode_t ad_hf_mode (mode_t mode)
291 {
292     /* fnctl lock need write access */
293     if ((mode & S_IRUSR))
294         mode |= S_IWUSR;
295     if ((mode & S_IRGRP))
296         mode |= S_IWGRP;
297     if ((mode & S_IROTH))
298         mode |= S_IWOTH;
299     /* if write mode set add read mode */
300     if ((mode & S_IWUSR))
301         mode |= S_IRUSR;
302     if ((mode & S_IWGRP))
303         mode |= S_IRGRP;
304     if ((mode & S_IWOTH))
305         mode |= S_IROTH;
306
307     return mode;
308 }
309
310 #endif
311
312 /* ------------------------------------- 
313   read in the entries 
314 */
315 static void parse_entries(struct adouble *ad, char *buf,
316                                     u_int16_t nentries)
317 {
318     u_int32_t   eid, len, off;
319     int         warning = 0;
320
321     /* now, read in the entry bits */
322     for (; nentries > 0; nentries-- ) {
323         memcpy(&eid, buf, sizeof( eid ));
324         eid = ntohl( eid );
325         buf += sizeof( eid );
326         memcpy(&off, buf, sizeof( off ));
327         off = ntohl( off );
328         buf += sizeof( off );
329         memcpy(&len, buf, sizeof( len ));
330         len = ntohl( len );
331         buf += sizeof( len );
332
333         if ( 0 < eid && eid < ADEID_MAX ) {
334             ad->ad_eid[ eid ].ade_off = off;
335             ad->ad_eid[ eid ].ade_len = len;
336         } else if (!warning) {
337             warning = 1;
338             LOG(log_debug, logtype_default, "ad_refresh: nentries %hd  eid %d\n",
339                     nentries, eid );
340         }
341     }
342 }
343
344
345 /* this reads enough of the header so that we can figure out all of
346  * the entry lengths and offsets. once that's done, we just read/mmap
347  * the rest of the header in.
348  *
349  * NOTE: we're assuming that the resource fork is kept at the end of
350  *       the file. also, mmapping won't work for the hfs fs until it
351  *       understands how to mmap header files. */
352 static int ad_header_read(struct adouble *ad, struct stat *hst)
353 {
354     char                *buf = ad->ad_data;
355     u_int16_t           nentries;
356     int                 len;
357     ssize_t             header_len;
358     static int          warning = 0;
359     struct stat         st;
360
361     /* read the header */
362     if ((header_len = adf_pread( &ad->ad_hf, buf, sizeof(ad->ad_data), 0)) < 0) {
363         return -1;
364     }
365     if (header_len < AD_HEADER_LEN) {
366         errno = EIO;
367         return -1;
368     }
369
370     memcpy(&ad->ad_magic, buf, sizeof( ad->ad_magic ));
371     memcpy(&ad->ad_version, buf + ADEDOFF_VERSION, sizeof( ad->ad_version ));
372
373     /* tag broken v1 headers. just assume they're all right. 
374      * we detect two cases: null magic/version
375      *                      byte swapped magic/version
376      * XXX: in the future, you'll need the v1compat flag. 
377      * (ad->ad_flags & ADFLAGS_V1COMPAT) */
378     if (!ad->ad_magic && !ad->ad_version) {
379       if (!warning) {
380         LOG(log_debug, logtype_default, "notice: fixing up null v1 magic/version.");
381         warning++;
382       }
383       ad->ad_magic = AD_MAGIC;
384       ad->ad_version = AD_VERSION1;
385
386     } else if (ad->ad_magic == AD_MAGIC && ad->ad_version == AD_VERSION1) {
387       if (!warning) {
388         LOG(log_debug, logtype_default, "notice: fixing up byte-swapped v1 magic/version.");
389         warning++;
390       }
391
392     } else {
393       ad->ad_magic = ntohl( ad->ad_magic );
394       ad->ad_version = ntohl( ad->ad_version );
395     }
396
397     if ((ad->ad_magic != AD_MAGIC) || ((ad->ad_version != AD_VERSION1)
398 #if AD_VERSION == AD_VERSION2
399                                        && (ad->ad_version != AD_VERSION2)
400 #endif /* AD_VERSION == AD_VERSION2 */
401                                        )) {
402       errno = EIO;
403       LOG(log_debug, logtype_default, "ad_open: can't parse AppleDouble header.");
404       return -1;
405     }
406
407     memcpy(ad->ad_filler, buf + ADEDOFF_FILLER, sizeof( ad->ad_filler ));
408     memcpy(&nentries, buf + ADEDOFF_NENTRIES, sizeof( nentries ));
409     nentries = ntohs( nentries );
410
411     /* read in all the entry headers. if we have more than the 
412      * maximum, just hope that the rfork is specified early on. */
413     len = nentries*AD_ENTRY_LEN;
414
415     if (len + AD_HEADER_LEN > sizeof(ad->ad_data))
416       len = sizeof(ad->ad_data) - AD_HEADER_LEN;
417
418     buf += AD_HEADER_LEN;
419     if (len > header_len - AD_HEADER_LEN) {
420         errno = EIO;
421         LOG(log_debug, logtype_default, "ad_header_read: can't read entry info.");
422         return -1;
423     }
424
425     /* figure out all of the entry offsets and lengths. if we aren't
426      * able to read a resource fork entry, bail. */
427     nentries = len / AD_ENTRY_LEN;
428     parse_entries(ad, buf, nentries);
429     if (!ad_getentryoff(ad, ADEID_RFORK)
430         || (ad_getentryoff(ad, ADEID_RFORK) > sizeof(ad->ad_data))
431         ) {
432       LOG(log_debug, logtype_default, "ad_header_read: problem with rfork entry offset."); 
433       return -1;
434     }
435
436     if (ad_getentryoff(ad, ADEID_RFORK) > header_len) {
437         errno = EIO;
438         LOG(log_debug, logtype_default, "ad_header_read: can't read in entries.");
439         return -1;
440     }
441     
442     if (hst == NULL) {
443         hst = &st;
444         if (fstat(ad->ad_hf.adf_fd, &st) < 0) {
445             return 1; /* fail silently */
446          }
447     }
448     ad->ad_rlen = hst->st_size - ad_getentryoff(ad, ADEID_RFORK);
449
450     /* fix up broken dates */
451     if (ad->ad_version == AD_VERSION1) {
452       u_int32_t aint;
453       
454       /* check to see if the ad date is wrong. just see if we have
455       * a modification date in the future. */
456       if (((ad_getdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, &aint)) == 0) &&
457           (aint > TIMEWARP_DELTA + hst->st_mtime)) {
458         ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, aint - AD_DATE_DELTA);
459         ad_getdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, &aint);
460         ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, aint - AD_DATE_DELTA);
461         ad_getdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, &aint);
462         ad_setdate(ad, AD_DATE_BACKUP | AD_DATE_UNIX, aint - AD_DATE_DELTA);
463       }
464     }
465
466     return 0;
467 }
468
469
470 /*
471  * Put the .AppleDouble where it needs to be:
472  *
473  *          /   a/.AppleDouble/b
474  *      a/b
475  *          \   b/.AppleDouble/.Parent
476  */
477 char *
478 ad_path( path, adflags )
479     const char  *path;
480     int         adflags;
481 {
482     static char pathbuf[ MAXPATHLEN + 1];
483     char        c, *slash, buf[MAXPATHLEN + 1];
484
485     strncpy(buf, path, MAXPATHLEN);
486     if ( adflags & ADFLAGS_DIR ) {
487         strncpy( pathbuf, buf, MAXPATHLEN );
488         if ( *buf != '\0' ) {
489             strcat( pathbuf, "/" );
490         }
491         slash = ".Parent";
492     } else {
493         if (NULL != ( slash = strrchr( buf, '/' )) ) {
494             c = *++slash;
495             *slash = '\0';
496             strncpy( pathbuf, buf, MAXPATHLEN);
497             *slash = c;
498         } else {
499             pathbuf[ 0 ] = '\0';
500             slash = buf;
501         }
502     }
503     strncat( pathbuf, ".AppleDouble/", MAXPATHLEN - strlen(pathbuf));
504     strncat( pathbuf, slash, MAXPATHLEN - strlen(pathbuf));
505
506     return( pathbuf );
507 }
508
509 /*
510  * Support inherited protection modes for AppleDouble files.  The supplied
511  * mode is ANDed with the parent directory's mask value in lieu of "umask",
512  * and that value is returned.
513  */
514
515 #define DEFMASK 07700   /* be conservative */
516
517 char 
518 *ad_dir(path)
519     const char          *path;
520 {
521     static char         modebuf[ MAXPATHLEN + 1];
522     char                *slash;
523
524     if ( strlen( path ) >= MAXPATHLEN ) {
525         errno = ENAMETOOLONG;
526         return NULL;  /* can't do it */
527     }
528
529     /*
530      * For a path with directories in it, remove the final component
531      * (path or subdirectory name) to get the name we want to stat.
532      * For a path which is just a filename, use "." instead.
533      */
534     strcpy( modebuf, path );
535     if (NULL != ( slash = strrchr( modebuf, '/' )) ) {
536         *slash = '\0';          /* remove pathname component */
537     } else {
538         modebuf[0] = '.';       /* use current directory */
539         modebuf[1] = '\0';
540     }
541     return modebuf;
542 }
543
544 /* ---------------- */
545 static uid_t default_uid = -1;
546
547 int ad_setfuid(const uid_t id)
548 {
549     default_uid = id;
550     return 0;
551 }
552
553 /* ---------------- */
554 uid_t ad_getfuid(void) 
555 {
556     return default_uid;
557 }
558
559 /* ---------------- 
560    return inode of path parent directory
561 */
562 static int ad_stat(const char *path, struct stat *stbuf)
563 {
564     char                *p;
565
566     p = ad_dir(path);
567     if (!p) {
568         return -1;
569     }
570
571     return stat( p, stbuf );
572 }
573
574 /* ---------------- 
575    if we are root change path user/ group
576    It can be a native function for BSD cf. FAQ.Q10
577    path:  pathname to chown 
578    stbuf: parent directory inode
579    
580    use fstat and fchown or lchown with linux?
581 */
582 #define EMULATE_SUIDDIR
583  
584 static int ad_chown(const char *path, struct stat *stbuf)
585 {
586 int ret = 0;
587 #ifdef EMULATE_SUIDDIR
588 uid_t id;
589
590     if (default_uid != -1) {  
591         /* we are root (admin) */
592         id = (default_uid)?default_uid:stbuf->st_uid;
593         ret = chown( path, id, stbuf->st_gid );
594     }
595 #endif    
596     return ret;
597 }
598
599 /* ---------------- 
600    return access right and inode of path parent directory
601 */
602 static int ad_mode_st(const char *path, int *mode, struct stat *stbuf)
603 {
604     if (*mode == 0) {
605        return -1;
606     }
607     if (ad_stat(path, stbuf) != 0) {
608         *mode &= DEFMASK;
609         return -1;
610     }
611     *mode &= stbuf->st_mode;
612     return 0;    
613 }
614
615 /* ---------------- 
616    return access right of path parent directory
617 */
618 int
619 ad_mode( path, mode )
620     const char          *path;
621     int                 mode;
622 {
623     struct stat         stbuf;
624     ad_mode_st(path, &mode, &stbuf);
625     return mode;
626 }
627
628 /*
629  * Use mkdir() with mode bits taken from ad_mode().
630  */
631 int
632 ad_mkdir( path, mode )
633     const char          *path;
634     int                 mode;
635 {
636 int ret;
637 int st_invalid;
638 struct stat stbuf;
639
640 #ifdef DEBUG
641     LOG(log_info, logtype_default, "ad_mkdir: Creating directory with mode %d", mode);
642 #endif /* DEBUG */
643
644     st_invalid = ad_mode_st(path, &mode, &stbuf);
645     ret = mkdir( path, mode );
646     if (ret || st_invalid)
647         return ret;
648     ad_chown(path, &stbuf);
649
650     return ret;    
651 }
652
653 /* ----------------- */
654 static int ad_error(struct adouble *ad, int adflags)
655 {
656     if ((adflags & ADFLAGS_NOHF)) {
657         /* FIXME double check : set header offset ?*/
658         return 0;
659     }
660     if ((adflags & ADFLAGS_DF)) {
661         ad_close( ad, ADFLAGS_DF );
662     }
663     return -1 ;
664 }
665
666 static int new_rfork(const char *path, struct adouble *ad, int adflags);
667
668 #ifdef  HAVE_PREAD
669 #define AD_SET(a) 
670 #else 
671 #define AD_SET(a) a = 0
672 #endif
673 /*
674  * It's not possible to open the header file O_RDONLY -- the read
675  * will fail and return an error. this refcounts things now. 
676  */
677 int ad_open( path, adflags, oflags, mode, ad )
678     const char          *path;
679     int                 adflags, oflags, mode;
680     struct adouble      *ad;
681 {
682     struct stat         st;
683     char                *slash, *ad_p;
684     int                 hoflags, admode;
685     int                 st_invalid;
686     int                 open_df = 0;
687     
688     if (ad->ad_inited != AD_INITED) {
689         ad_dfileno(ad) = -1;
690         ad_hfileno(ad) = -1;
691         adf_lock_init(&ad->ad_df);
692         adf_lock_init(&ad->ad_hf);
693         ad->ad_inited = AD_INITED;
694         ad->ad_refcount = 1;
695     }
696
697     if ((adflags & ADFLAGS_DF)) { 
698         if (ad_dfileno(ad) == -1) {
699           hoflags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
700           admode = mode;
701           st_invalid = ad_mode_st(path, &admode, &st);
702           ad->ad_df.adf_fd =open( path, hoflags, admode );
703           if (ad->ad_df.adf_fd < 0 ) {
704              if (errno == EACCES && !(oflags & O_RDWR)) {
705                 hoflags = oflags;
706                 ad->ad_df.adf_fd =open( path, hoflags, admode );
707              }
708           }
709           if ( ad->ad_df.adf_fd < 0)
710                 return -1;
711
712           AD_SET(ad->ad_df.adf_off);
713           ad->ad_df.adf_flags = hoflags;
714           if ((oflags & O_CREAT) && !st_invalid) {
715               /* just created, set owner if admin (root) */
716               ad_chown(path, &st);
717           }
718         } 
719         else {
720             /* the file is already open... but */
721             if ((oflags & ( O_RDWR | O_WRONLY)) &&             /* we want write access */
722                 !(ad->ad_df.adf_flags & ( O_RDWR | O_WRONLY))) /* and it was denied the first time */
723             {
724                  errno = EACCES;
725                  return -1;
726             }
727             /* FIXME 
728              * for now ad_open is never called with O_TRUNC or O_EXCL if the file is
729              * already open. Should we check for it? ie
730              * O_EXCL --> error 
731              * O_TRUNC --> truncate the fork.
732              * idem for ressource fork.
733              */
734         }
735         open_df = ADFLAGS_DF;
736         ad->ad_df.adf_refcount++;
737     }
738
739     if (!(adflags & ADFLAGS_HF)) 
740         return 0;
741         
742     if (ad_hfileno(ad) != -1) { /* the file is already open */
743         if ((oflags & ( O_RDWR | O_WRONLY)) &&             
744                 !(ad->ad_hf.adf_flags & ( O_RDWR | O_WRONLY))) {
745             if (open_df) {
746                 /* don't call with ADFLAGS_HF because we didn't open ressource fork */
747                 ad_close( ad, open_df );
748             }
749             errno = EACCES;
750             return -1;
751         }
752         ad_refresh(ad);
753         ad->ad_hf.adf_refcount++;
754         return 0;
755     }
756
757     ad_p = ad_path( path, adflags );
758
759     hoflags = oflags & ~O_CREAT;
760     hoflags = (hoflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
761     ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
762     if (ad->ad_hf.adf_fd < 0 ) {
763         if (errno == EACCES && !(oflags & O_RDWR)) {
764             hoflags = oflags & ~O_CREAT;
765             ad->ad_hf.adf_fd = open( ad_p, hoflags, 0 );
766         }    
767     }
768
769     if ( ad->ad_hf.adf_fd < 0 ) { 
770         if (errno == ENOENT && (oflags & O_CREAT) ) {
771             /*
772              * We're expecting to create a new adouble header file,
773              * here.
774              * if ((oflags & O_CREAT) ==> (oflags & O_RDWR)
775              */
776             admode = mode;
777             st_invalid = ad_mode_st(ad_p, &admode, &st);
778             admode = ad_hf_mode(admode); 
779             errno = 0;
780             ad->ad_hf.adf_fd = open( ad_p, oflags,admode );
781             if ( ad->ad_hf.adf_fd < 0 ) {
782                 /*
783                  * Probably .AppleDouble doesn't exist, try to
784                  * mkdir it.
785                  */
786                 if (errno == ENOENT && (adflags & ADFLAGS_NOADOUBLE) == 0) {
787                     if (NULL == ( slash = strrchr( ad_p, '/' )) ) {
788                         return ad_error(ad, adflags);
789                     }
790                     *slash = '\0';
791                     errno = 0;
792                     if ( ad_mkdir( ad_p, 0777 ) < 0 ) {
793                         return ad_error(ad, adflags);
794                     }
795                     *slash = '/';
796                     admode = mode;
797                     st_invalid = ad_mode_st(ad_p, &admode, &st);
798                     admode = ad_hf_mode(admode); 
799                     ad->ad_hf.adf_fd = open( ad_p, oflags, admode);
800                     if ( ad->ad_hf.adf_fd < 0 ) {
801                         return ad_error(ad, adflags);
802                     }
803                 } else {
804                      return ad_error(ad, adflags);
805                 }
806             }
807             ad->ad_hf.adf_flags = oflags;
808             /* just created, set owner if admin owner (root) */
809             if (!st_invalid) {
810                 ad_chown(path, &st);
811             }
812         }
813         else {
814             return ad_error(ad, adflags);
815         }
816     } else if (fstat(ad->ad_hf.adf_fd, &st) == 0 && st.st_size == 0) {
817         /* for 0 length files, treat them as new. */
818         ad->ad_hf.adf_flags = (oflags & ~(O_RDONLY | O_WRONLY)) | O_RDWR | O_TRUNC;
819     } else {
820         ad->ad_hf.adf_flags = hoflags;
821     }
822     AD_SET(ad->ad_hf.adf_off);
823           
824     memset(ad->ad_eid, 0, sizeof( ad->ad_eid ));
825     ad->ad_hf.adf_refcount++;
826     if ((ad->ad_hf.adf_flags & ( O_TRUNC | O_CREAT ))) {
827         /*
828          * This is a new adouble header file. Initialize the structure,
829          * instead of reading it.
830         */
831         if (new_rfork(path, ad, adflags) < 0) {
832             /* the file is already deleted, perm, whatever, so return an error*/
833             ad_close(ad, adflags);
834             return -1;
835         }
836     } else {
837             /* Read the adouble header in and parse it.*/
838         if ((ad_header_read( ad , &st) < 0)
839 #if AD_VERSION == AD_VERSION2
840                 || (ad_v1tov2(ad, ad_p) < 0)
841 #endif /* AD_VERSION == AD_VERSION2 */
842         ) {
843             ad_close( ad, adflags );
844             return( -1 );
845         }
846     }
847     return 0 ;
848 }
849
850 /* ----------------------------------- */
851 static int new_rfork(const char *path, struct adouble *ad, int adflags)
852 {
853 #if 0
854     struct timeval      tv;
855 #endif    
856     const struct entry  *eid;
857     u_int16_t           ashort;
858     struct stat         st;
859
860     ad->ad_magic = AD_MAGIC;
861     ad->ad_version = AD_VERSION;
862
863     memset(ad->ad_filler, 0, sizeof( ad->ad_filler ));
864     memset(ad->ad_data, 0, sizeof(ad->ad_data));
865
866     eid = entry_order;
867     while (eid->id) {
868         ad->ad_eid[eid->id].ade_off = eid->offset;
869         ad->ad_eid[eid->id].ade_len = eid->len;
870         eid++;
871     }
872             
873     /* put something sane in the directory finderinfo */
874     if (adflags & ADFLAGS_DIR) {
875         /* set default view */
876         ashort = htons(FINDERINFO_CLOSEDVIEW);
877         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRVIEWOFF, 
878                      &ashort, sizeof(ashort));
879     } else {
880         /* set default creator/type fields */
881         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRTYPEOFF,"TEXT", 4);
882         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRCREATOFF,"UNIX", 4);
883     }
884
885     /* make things invisible */
886     if ((*path == '.') && strcmp(path, ".") && strcmp(path, "..")) {
887         ashort = htons(ATTRBIT_INVISIBLE);
888         ad_setattr(ad, ashort);
889         ashort = htons(FINDERINFO_INVISIBLE);
890         memcpy(ad_entry(ad, ADEID_FINDERI) + FINDERINFO_FRFLAGOFF,
891                      &ashort, sizeof(ashort));
892     }
893
894 #if 0
895     if (gettimeofday(&tv, NULL) < 0) {
896         return -1;
897     } 
898 #endif
899     
900     if (stat(path, &st) < 0) {
901         return -1;
902     }
903             
904     /* put something sane in the date fields */
905     ad_setdate(ad, AD_DATE_CREATE | AD_DATE_UNIX, st.st_mtime);
906     ad_setdate(ad, AD_DATE_MODIFY | AD_DATE_UNIX, st.st_mtime);
907     ad_setdate(ad, AD_DATE_ACCESS | AD_DATE_UNIX, st.st_mtime);
908     ad_setdate(ad, AD_DATE_BACKUP, AD_DATE_START);
909     return 0;
910 }
911
912 /* to do this with mmap, we need the hfs fs to understand how to mmap
913    header files. */
914 int ad_refresh(struct adouble *ad)
915 {
916
917   if (ad->ad_hf.adf_fd < -1)
918     return -1;
919
920   return ad_header_read(ad, NULL);
921 }