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