]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/directory.c
Fix handling of currentdir
[netatalk.git] / etc / afpd / directory.c
1 /*
2  * Copyright (c) 1990,1993 Regents of The University of Michigan.
3  * All Rights Reserved.  See COPYRIGHT.
4  */
5
6 #ifdef HAVE_CONFIG_H
7 #include "config.h"
8 #endif /* HAVE_CONFIG_H */
9
10 #include <string.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <grp.h>
14 #include <pwd.h>
15 #include <sys/param.h>
16 #include <sys/stat.h>
17 #include <errno.h>
18 #include <utime.h>
19 #include <assert.h>
20
21 #include <atalk/adouble.h>
22 #include <atalk/vfs.h>
23 #include <atalk/afp.h>
24 #include <atalk/util.h>
25 #include <atalk/cnid.h>
26 #include <atalk/logger.h>
27 #include <atalk/uuid.h>
28 #include <atalk/unix.h>
29 #include <atalk/bstrlib.h>
30 #include <atalk/bstradd.h>
31
32 #include "directory.h"
33 #include "dircache.h"
34 #include "desktop.h"
35 #include "volume.h"
36 #include "fork.h"
37 #include "file.h"
38 #include "filedir.h"
39 #include "globals.h"
40 #include "unix.h"
41 #include "mangle.h"
42 #include "hash.h"
43
44 /*
45  * FIXMEs, loose ends after the dircache rewrite:
46  * o merge dircache_search_by_name and dir_add ??
47  * o case-insensitivity is gone from cname
48  */
49
50
51 /*******************************************************************************************
52  * Globals
53  ******************************************************************************************/
54
55 int         afp_errno;
56 /* As long as directory.c hasn't got its own init call, this get initialized in dircache_init */
57 struct dir rootParent  = {
58     NULL, NULL, NULL, NULL,          /* path, d_m_name, d_u_name, d_m_name_ucs2 */
59     NULL, 0, 0,                      /* qidx_node, ctime, d_flags */
60     0, 0, 0, 0                       /* pdid, did, offcnt, d_vid */
61 };
62 struct dir  *curdir = &rootParent;
63 struct path Cur_Path = {
64     0,
65     "",  /* mac name */
66     ".", /* unix name */
67     0,   /* id */
68     NULL,/* struct dir * */
69     0,   /* stat is not set */
70     0,   /* errno */
71     {0} /* struct stat */
72 };
73
74 /*
75  * dir_remove queues struct dirs to be freed here. We can't just delete them immeidately
76  * eg in dircache_search_by_id, because a caller somewhere up the stack might be
77  * referencing it.
78  * So instead:
79  * - we mark it as invalid by setting d_did to CNID_INVALID (ie 0)
80  * - queue it in "invalid_dircache_entries" queue
81  * - which is finally freed at the end of every AFP func in afp_dsi.c.
82  */
83 q_t *invalid_dircache_entries;
84
85
86 /*******************************************************************************************
87  * Locals
88  ******************************************************************************************/
89
90
91 /* -------------------------
92    appledouble mkdir afp error code.
93 */
94 static int netatalk_mkdir(const struct vol *vol, const char *name)
95 {
96     int ret;
97     struct stat st;
98
99     if (vol->v_flags & AFPVOL_UNIX_PRIV) {
100         if (lstat(".", &st) < 0)
101             return AFPERR_MISC;
102         int mode = (DIRBITS & (~S_ISGID & st.st_mode)) | (0777 & ~vol->v_umask);
103         LOG(log_maxdebug, logtype_afpd, "netatalk_mkdir(\"%s\") {parent mode: %04o, vol umask: %04o}",
104             name, st.st_mode, vol->v_umask);
105
106         ret = mkdir(name, mode);
107     } else {
108         ret = ad_mkdir(name, DIRBITS | 0777);
109     }
110
111     if (ret < 0) {
112         switch ( errno ) {
113         case ENOENT :
114             return( AFPERR_NOOBJ );
115         case EROFS :
116             return( AFPERR_VLOCK );
117         case EPERM:
118         case EACCES :
119             return( AFPERR_ACCESS );
120         case EEXIST :
121             return( AFPERR_EXIST );
122         case ENOSPC :
123         case EDQUOT :
124             return( AFPERR_DFULL );
125         default :
126             return( AFPERR_PARAM );
127         }
128     }
129     return AFP_OK;
130 }
131
132 /* ------------------- */
133 static int deletedir(int dirfd, char *dir)
134 {
135     char path[MAXPATHLEN + 1];
136     DIR *dp;
137     struct dirent   *de;
138     struct stat st;
139     size_t len;
140     int err = AFP_OK;
141     size_t remain;
142
143     if ((len = strlen(dir)) +2 > sizeof(path))
144         return AFPERR_PARAM;
145
146     /* already gone */
147     if ((dp = opendirat(dirfd, dir)) == NULL)
148         return AFP_OK;
149
150     strcpy(path, dir);
151     strcat(path, "/");
152     len++;
153     remain = sizeof(path) -len -1;
154     while ((de = readdir(dp)) && err == AFP_OK) {
155         /* skip this and previous directory */
156         if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
157             continue;
158
159         if (strlen(de->d_name) > remain) {
160             err = AFPERR_PARAM;
161             break;
162         }
163         strcpy(path + len, de->d_name);
164         if (lstatat(dirfd, path, &st)) {
165             continue;
166         }
167         if (S_ISDIR(st.st_mode)) {
168             err = deletedir(dirfd, path);
169         } else {
170             err = netatalk_unlinkat(dirfd, path);
171         }
172     }
173     closedir(dp);
174
175     /* okay. the directory is empty. delete it. note: we already got rid
176        of .AppleDouble.  */
177     if (err == AFP_OK) {
178         err = netatalk_rmdir(dirfd, dir);
179     }
180     return err;
181 }
182
183 /* do a recursive copy. */
184 static int copydir(const struct vol *vol, int dirfd, char *src, char *dst)
185 {
186     char spath[MAXPATHLEN + 1], dpath[MAXPATHLEN + 1];
187     DIR *dp;
188     struct dirent   *de;
189     struct stat st;
190     struct utimbuf      ut;
191     size_t slen, dlen;
192     size_t srem, drem;
193     int err;
194
195     /* doesn't exist or the path is too long. */
196     if (((slen = strlen(src)) > sizeof(spath) - 2) ||
197         ((dlen = strlen(dst)) > sizeof(dpath) - 2) ||
198         ((dp = opendirat(dirfd, src)) == NULL))
199         return AFPERR_PARAM;
200
201     /* try to create the destination directory */
202     if (AFP_OK != (err = netatalk_mkdir(vol, dst)) ) {
203         closedir(dp);
204         return err;
205     }
206
207     /* set things up to copy */
208     strcpy(spath, src);
209     strcat(spath, "/");
210     slen++;
211     srem = sizeof(spath) - slen -1;
212
213     strcpy(dpath, dst);
214     strcat(dpath, "/");
215     dlen++;
216     drem = sizeof(dpath) - dlen -1;
217
218     err = AFP_OK;
219     while ((de = readdir(dp))) {
220         /* skip this and previous directory */
221         if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
222             continue;
223
224         if (strlen(de->d_name) > srem) {
225             err = AFPERR_PARAM;
226             break;
227         }
228         strcpy(spath + slen, de->d_name);
229
230         if (lstatat(dirfd, spath, &st) == 0) {
231             if (strlen(de->d_name) > drem) {
232                 err = AFPERR_PARAM;
233                 break;
234             }
235             strcpy(dpath + dlen, de->d_name);
236
237             if (S_ISDIR(st.st_mode)) {
238                 if (AFP_OK != (err = copydir(vol, dirfd, spath, dpath)))
239                     goto copydir_done;
240             } else if (AFP_OK != (err = copyfile(vol, vol, dirfd, spath, dpath, NULL, NULL))) {
241                 goto copydir_done;
242
243             } else {
244                 /* keep the same time stamp. */
245                 ut.actime = ut.modtime = st.st_mtime;
246                 utime(dpath, &ut);
247             }
248         }
249     }
250
251     /* keep the same time stamp. */
252     if (lstatat(dirfd, src, &st) == 0) {
253         ut.actime = ut.modtime = st.st_mtime;
254         utime(dst, &ut);
255     }
256
257 copydir_done:
258     closedir(dp);
259     return err;
260 }
261
262 /* ---------------------
263  * is our cached offspring count valid?
264  */
265 static int diroffcnt(struct dir *dir, struct stat *st)
266 {
267     return st->st_ctime == dir->ctime;
268 }
269
270 /* --------------------- */
271 static int invisible_dots(const struct vol *vol, const char *name)
272 {
273     return vol_inv_dots(vol) && *name  == '.' && strcmp(name, ".") && strcmp(name, "..");
274 }
275
276 /* ------------------ */
277 static int set_dir_errors(struct path *path, const char *where, int err)
278 {
279     switch ( err ) {
280     case EPERM :
281     case EACCES :
282         return AFPERR_ACCESS;
283     case EROFS :
284         return AFPERR_VLOCK;
285     }
286     LOG(log_error, logtype_afpd, "setdirparam(%s): %s: %s", fullpathname(path->u_name), where, strerror(err) );
287     return AFPERR_PARAM;
288 }
289
290 /*!
291  * @brief Convert name in client encoding to server encoding
292  *
293  * Convert ret->m_name to ret->u_name from client encoding to server encoding.
294  * This only gets called from cname().
295  *
296  * @returns 0 on success, -1 on error
297  *
298  * @note If the passed ret->m_name is mangled, we'll demangle it
299  */
300 static int cname_mtouname(const struct vol *vol, const struct dir *dir, struct path *ret, int toUTF8)
301 {
302     static char temp[ MAXPATHLEN + 1];
303     char *t;
304     cnid_t fileid = 0;
305
306     if (afp_version >= 30) {
307         if (toUTF8) {
308             if (dir->d_did == DIRDID_ROOT_PARENT) {
309                 /*
310                  * With uft8 volume name is utf8-mac, but requested path may be a mangled longname. See #2611981.
311                  * So we compare it with the longname from the current volume and if they match
312                  * we overwrite the requested path with the utf8 volume name so that the following
313                  * strcmp can match.
314                  */
315                 ucs2_to_charset(vol->v_maccharset, vol->v_macname, temp, AFPVOL_MACNAMELEN + 1);
316                 if (strcasecmp(ret->m_name, temp) == 0)
317                     ucs2_to_charset(CH_UTF8_MAC, vol->v_u8mname, ret->m_name, AFPVOL_U8MNAMELEN);
318             } else {
319                 /* toUTF8 */
320                 if (mtoUTF8(vol, ret->m_name, strlen(ret->m_name), temp, MAXPATHLEN) == (size_t)-1) {
321                     afp_errno = AFPERR_PARAM;
322                     return -1;
323                 }
324                 strcpy(ret->m_name, temp);
325             }
326         }
327
328         /* check for OS X mangled filename :( */
329         t = demangle_osx(vol, ret->m_name, dir->d_did, &fileid);
330         LOG(log_maxdebug, logtype_afpd, "cname_mtouname('%s',did:%u) {demangled:'%s', fileid:%u}",
331             ret->m_name, ntohl(dir->d_did), t, ntohl(fileid));
332
333         if (t != ret->m_name) {
334             ret->u_name = t;
335             /* duplicate work but we can't reuse all convert_char we did in demangle_osx
336              * flags weren't the same
337              */
338             if ( (t = utompath(vol, ret->u_name, fileid, utf8_encoding())) ) {
339                 /* at last got our view of mac name */
340                 strcpy(ret->m_name, t);
341             }
342         }
343     } /* afp_version >= 30 */
344
345     /* If we haven't got it by now, get it */
346     if (ret->u_name == NULL) {
347         if ((ret->u_name = mtoupath(vol, ret->m_name, dir->d_did, utf8_encoding())) == NULL) {
348             afp_errno = AFPERR_PARAM;
349             return -1;
350         }
351     }
352
353     return 0;
354 }
355
356 /*!
357  * @brief Build struct path from struct dir
358  *
359  * The final movecwd in cname failed, possibly with EPERM or ENOENT. We:
360  * 1. move cwd into parent dir (we're often already there, but not always)
361  * 2. set struct path to the dirname
362  * 3. in case of
363  *    AFPERR_ACCESS: the dir is there, we just cant chdir into it
364  *    AFPERR_NOOBJ: the dir was there when we stated it in cname, so we have a race
365  *                  4. indicate there's no dir for this path
366  *                  5. remove the dir
367  */
368 static struct path *path_from_dir(struct vol *vol, struct dir *dir, struct path *ret)
369 {
370     if (dir->d_did == DIRDID_ROOT_PARENT || dir->d_did == DIRDID_ROOT)
371         return NULL;
372
373     switch (afp_errno) {
374
375     case AFPERR_ACCESS:
376         if (movecwd( vol, dirlookup(vol, dir->d_pdid)) < 0 ) /* 1 */
377             return NULL;
378
379         memcpy(ret->m_name, cfrombstr(dir->d_m_name), blength(dir->d_m_name) + 1); /* 3 */
380         if (dir->d_m_name == dir->d_u_name) {
381             ret->u_name = ret->m_name;
382         } else {
383             ret->u_name =  ret->m_name + blength(dir->d_m_name) + 1;
384             memcpy(ret->u_name, cfrombstr(dir->d_u_name), blength(dir->d_u_name) + 1);
385         }
386
387         ret->d_dir = dir;
388
389         LOG(log_debug, logtype_afpd, "cname('%s') {path-from-dir: AFPERR_ACCESS. curdir:'%s', path:'%s'}",
390             cfrombstr(dir->d_fullpath),
391             cfrombstr(curdir->d_fullpath),
392             ret->u_name);
393
394         return ret;
395
396     case AFPERR_NOOBJ:
397         if (movecwd(vol, dirlookup(vol, dir->d_pdid)) < 0 ) /* 1 */
398             return NULL;
399
400         memcpy(ret->m_name, cfrombstr(dir->d_m_name), blength(dir->d_m_name) + 1);
401         if (dir->d_m_name == dir->d_u_name) {
402             ret->u_name = ret->m_name;
403         } else {
404             ret->u_name =  ret->m_name + blength(dir->d_m_name) + 1;
405             memcpy(ret->u_name, cfrombstr(dir->d_u_name), blength(dir->d_u_name) + 1);
406         }
407
408         ret->d_dir = NULL;      /* 4 */
409         dir_remove(vol, dir);   /* 5 */
410         return ret;
411
412     default:
413         return NULL;
414     }
415
416     /* DEADC0DE: never get here */
417     return NULL;
418 }
419
420
421 /*********************************************************************************************
422  * Interface
423  ********************************************************************************************/
424
425 int get_afp_errno(const int param)
426 {
427     if (afp_errno != AFPERR_DID1)
428         return afp_errno;
429     return param;
430 }
431
432 /*!
433  * @brief Resolve a DID
434  *
435  * Resolve a DID, allocate a struct dir for it
436  * 1. Check for special CNIDs 0 (invalid), 1 and 2.
437  * 2a. Check if the DID is in the cache.
438  * 2b. Check if it's really a dir (d_fullpath != NULL) because we cache files too.
439  * 3. If it's not in the cache resolve it via the database.
440  * 4. Build complete server-side path to the dir.
441  * 5. Check if it exists and is a directory.
442  * 6. Create the struct dir and populate it.
443  * 7. Add it to the cache.
444  *
445  * @param vol   (r) pointer to struct vol
446  * @param did   (r) DID to resolve
447  *
448  * @returns pointer to struct dir
449  *
450  * @note FIXME: OSX calls it with bogus id, ie file ID not folder ID,
451  *       and we are really bad in this case.
452  */
453 struct dir *dirlookup(const struct vol *vol, cnid_t did)
454 {
455     static char  buffer[12 + MAXPATHLEN + 1];
456     struct stat  st;
457     struct dir   *ret = NULL, *pdir;
458     bstring      fullpath = NULL;
459     char         *upath = NULL, *mpath;
460     cnid_t       cnid, pdid;
461     size_t       maxpath;
462     int          buflen = 12 + MAXPATHLEN + 1;
463     int          utf8;
464     int          err = 0;
465
466     LOG(log_debug, logtype_afpd, "dirlookup(did: %u)", ntohl(did));
467
468     /* check for did 0, 1 and 2 */
469     if (did == 0 || vol == NULL) { /* 1 */
470         afp_errno = AFPERR_PARAM;
471         ret = NULL;
472         goto exit;
473     } else if (did == DIRDID_ROOT_PARENT) {
474         rootParent.d_vid = vol->v_vid;
475         ret = &rootParent;
476         goto exit;
477     } else if (did == DIRDID_ROOT) {
478         ret = vol->v_root;
479         goto exit;
480     }
481
482     /* Search the cache */
483     if ((ret = dircache_search_by_did(vol, did)) != NULL) { /* 2a */
484         if (ret->d_fullpath == NULL) {                      /* 2b */
485             afp_errno = AFPERR_BADTYPE;
486             ret = NULL;
487             goto exit;
488         }
489         if (lstat(cfrombstr(ret->d_fullpath), &st) != 0) {
490             LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {lstat: %s}", ntohl(did), strerror(errno));
491             switch (errno) {
492             case ENOENT:
493             case ENOTDIR:
494                 /* It's not there anymore, so remove it */
495                 LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {calling dir_remove()}", ntohl(did));
496                 dir_remove(vol, ret);
497                 afp_errno = AFPERR_NOOBJ;
498                 ret = NULL;
499                 goto exit;
500             default:
501                 ret = ret;
502                 goto exit;
503             }
504             /* DEADC0DE */
505             ret = NULL;
506             goto exit;            
507         }
508         ret = ret;
509         goto exit;
510     }
511
512     utf8 = utf8_encoding();
513     maxpath = (utf8) ? MAXPATHLEN - 7 : 255;
514
515     /* Get it from the database */
516     cnid = did;
517     if ( (upath = cnid_resolve(vol->v_cdb, &cnid, buffer, buflen)) == NULL 
518          || (upath = strdup(upath)) == NULL) { /* 3 */
519         afp_errno = AFPERR_NOOBJ;
520         err = 1;
521         goto exit;
522     }
523     pdid = cnid;
524
525     /*
526      * Recurse up the tree, terminates in dirlookup when either
527      * - DIRDID_ROOT is hit
528      * - a cached entry is found
529      */
530     if ((pdir = dirlookup(vol, pdid)) == NULL) {
531         err = 1;
532         goto exit;
533     }
534
535     /* build the fullpath */
536     if ((fullpath = bstrcpy(pdir->d_fullpath)) == NULL
537         || bconchar(fullpath, '/') != BSTR_OK
538         || bcatcstr(fullpath, upath) != BSTR_OK) {
539         err = 1;
540         goto exit;
541     }
542
543     /* stat it and check if it's a dir */
544     LOG(log_debug, logtype_afpd, "dirlookup: {stating %s}", cfrombstr(fullpath));
545
546     if (stat(cfrombstr(fullpath), &st) != 0) { /* 5a */
547         switch (errno) {
548         case ENOENT:
549             afp_errno = AFPERR_NOOBJ;
550             err = 1;
551             goto exit;
552         case EPERM:
553             afp_errno = AFPERR_ACCESS;
554             err = 1;
555             goto exit;
556         default:
557             afp_errno = AFPERR_MISC;
558             err = 1;
559             goto exit;
560         }
561     } else {
562         if ( ! S_ISDIR(st.st_mode)) { /* 5b */
563             afp_errno = AFPERR_BADTYPE;
564             err = 1;
565             goto exit;
566         }
567     }
568
569     /* Get macname from unix name */
570     if ( (mpath = utompath(vol, upath, did, utf8)) == NULL ) {
571         afp_errno = AFPERR_NOOBJ;
572         err = 1;
573         goto exit;
574     }
575
576     /* Create struct dir */
577     if ((ret = dir_new(mpath, upath, vol, pdid, did, fullpath, st.st_ctime)) == NULL) { /* 6 */
578         LOG(log_error, logtype_afpd, "dirlookup(did: %u) {%s, %s}: %s", ntohl(did), mpath, upath, strerror(errno));
579         err = 1;
580         goto exit;
581     }
582     
583     /* Add it to the cache only if it's a dir */
584     if (dircache_add(vol, ret) != 0) { /* 7 */
585         err = 1;
586         goto exit;
587     }
588
589 exit:
590     if (upath) free(upath);
591     if (err) {
592         LOG(log_debug, logtype_afpd, "dirlookup(did: %u) {exit_error: %s}",
593             ntohl(did), AfpErr2name(afp_errno));
594         if (fullpath)
595             bdestroy(fullpath);
596         if (ret) {
597             dir_free(ret);
598             ret = NULL;
599         }
600     }
601     if (ret)
602         LOG(log_debug, logtype_afpd, "dirlookup(did: %u): pdid: %u, \"%s\"",
603             ntohl(ret->d_did), ntohl(ret->d_pdid), cfrombstr(ret->d_fullpath));
604
605     return ret;
606 }
607
608 #define ENUMVETO "./../Network Trash Folder/TheVolumeSettingsFolder/TheFindByContentFolder/:2eDS_Store/Contents/Desktop Folder/Trash/Benutzer/"
609
610 int caseenumerate(const struct vol *vol, struct path *path, struct dir *dir)
611 {
612     DIR               *dp;
613     struct dirent     *de;
614     int               ret;
615     static u_int32_t  did = 0;
616     static char       cname[MAXPATHLEN];
617     static char       lname[MAXPATHLEN];
618     ucs2_t        u2_path[MAXPATHLEN];
619     ucs2_t        u2_dename[MAXPATHLEN];
620     char          *tmp, *savepath;
621
622     if (!(vol->v_flags & AFPVOL_CASEINSEN))
623         return -1;
624
625     if (veto_file(ENUMVETO, path->u_name))
626         return -1;
627
628     savepath = path->u_name;
629
630     /* very simple cache */
631     if ( dir->d_did == did && strcmp(lname, path->u_name) == 0) {
632         path->u_name = cname;
633         path->d_dir = NULL;
634         if (of_stat( path ) == 0 ) {
635             return 0;
636         }
637         /* something changed, we cannot stat ... */
638         did = 0;
639     }
640
641     if (NULL == ( dp = opendir( "." )) ) {
642         LOG(log_debug, logtype_afpd, "caseenumerate: opendir failed: %s", dir->d_u_name);
643         return -1;
644     }
645
646
647     /* LOG(log_debug, logtype_afpd, "caseenumerate: for %s", path->u_name); */
648     if ((size_t) -1 == convert_string(vol->v_volcharset, CH_UCS2, path->u_name, -1, u2_path, sizeof(u2_path)) )
649         LOG(log_debug, logtype_afpd, "caseenumerate: conversion failed for %s", path->u_name);
650
651     /*LOG(log_debug, logtype_afpd, "caseenumerate: dir: %s, path: %s", dir->d_u_name, path->u_name); */
652     ret = -1;
653     for ( de = readdir( dp ); de != NULL; de = readdir( dp )) {
654         if (NULL == check_dirent(vol, de->d_name))
655             continue;
656
657         if ((size_t) -1 == convert_string(vol->v_volcharset, CH_UCS2, de->d_name, -1, u2_dename, sizeof(u2_dename)) )
658             continue;
659
660         if (strcasecmp_w( u2_path, u2_dename) == 0) {
661             tmp = path->u_name;
662             strlcpy(cname, de->d_name, sizeof(cname));
663             path->u_name = cname;
664             path->d_dir = NULL;
665             if (of_stat( path ) == 0 ) {
666                 LOG(log_debug, logtype_afpd, "caseenumerate: using dir: %s, path: %s", de->d_name, path->u_name);
667                 strlcpy(lname, tmp, sizeof(lname));
668                 did = dir->d_did;
669                 ret = 0;
670                 break;
671             }
672             else
673                 path->u_name = tmp;
674         }
675
676     }
677     closedir(dp);
678
679     if (ret) {
680         /* invalidate cache */
681         cname[0] = 0;
682         did = 0;
683         path->u_name = savepath;
684     }
685     /* LOG(log_debug, logtype_afpd, "caseenumerate: path on ret: %s", path->u_name); */
686     return ret;
687 }
688
689
690 /*!
691  * @brief Construct struct dir
692  *
693  * Construct struct dir from parameters.
694  *
695  * @param m_name   (r) directory name in UTF8-dec
696  * @param u_name   (r) directory name in server side encoding
697  * @param vol      (r) pointer to struct vol
698  * @param pdid     (r) Parent CNID
699  * @param did      (r) CNID
700  * @param path     (r) Full unix path to dir or NULL for files
701  * @param ctime    (r) st_ctime from stat
702  *
703  * @returns pointer to new struct dir or NULL on error
704  *
705  * @note Most of the time mac name and unix name are the same.
706  */
707 struct dir *dir_new(const char *m_name,
708                     const char *u_name,
709                     const struct vol *vol,
710                     cnid_t pdid,
711                     cnid_t did,
712                     bstring path,
713                     time_t ctime)
714 {
715     struct dir *dir;
716
717     dir = (struct dir *) calloc(1, sizeof( struct dir ));
718     if (!dir)
719         return NULL;
720
721     if ((dir->d_m_name = bfromcstr(m_name)) == NULL) {
722         free(dir);
723         return NULL;
724     }
725
726     if (convert_string_allocate( (utf8_encoding()) ? CH_UTF8_MAC : vol->v_maccharset,
727                                  CH_UCS2,
728                                  m_name,
729                                  -1, (char **)&dir->d_m_name_ucs2) == (size_t)-1 ) {
730         LOG(log_error, logtype_afpd, "dir_new(did: %u) {%s, %s}: couldn't set UCS2 name", ntohl(did), m_name, u_name);
731         dir->d_m_name_ucs2 = NULL;
732     }
733
734     if (m_name == u_name || !strcmp(m_name, u_name)) {
735         dir->d_u_name = dir->d_m_name;
736     }
737     else if ((dir->d_u_name = bfromcstr(u_name)) == NULL) {
738         bdestroy(dir->d_m_name);
739         free(dir);
740         return NULL;
741     }
742
743     dir->d_did = did;
744     dir->d_pdid = pdid;
745     dir->d_vid = vol->v_vid;
746     dir->d_fullpath = path;
747     dir->ctime_dircache = ctime;
748     return dir;
749 }
750
751 /*!
752  * @brief Free a struct dir and all its members
753  *
754  * @param (rw) pointer to struct dir
755  */
756 void dir_free(struct dir *dir)
757 {
758     if (dir->d_u_name != dir->d_m_name) {
759         bdestroy(dir->d_u_name);
760     }
761     if (dir->d_m_name_ucs2)
762         free(dir->d_m_name_ucs2);
763     bdestroy(dir->d_m_name);
764     bdestroy(dir->d_fullpath);
765     free(dir);
766 }
767
768 /*!
769  * @brief Create struct dir from struct path
770  *
771  * Create a new struct dir from struct path. Then add it to the cache.
772  *
773  * 1. Open adouble file, get CNID from it.
774  * 2. Search the database, hinting with the CNID from (1).
775  * 3. Build fullpath and create struct dir.
776  * 4. Add it to the cache.
777  *
778  * @param vol   (r) pointer to struct vol, possibly modified in callee
779  * @param dir   (r) pointer to parrent directory
780  * @param path  (rw) pointer to struct path with valid path->u_name
781  * @param len   (r) strlen of path->u_name
782  *
783  * @returns Pointer to new struct dir or NULL on error.
784  *
785  * @note Function also assigns path->m_name from path->u_name.
786  */
787 struct dir *dir_add(struct vol *vol, const struct dir *dir, struct path *path, int len)
788 {
789     int err = 0;
790     struct dir  *cdir = NULL;
791     cnid_t      id;
792     struct adouble  ad;
793     struct adouble *adp = NULL;
794     bstring fullpath;
795
796     AFP_ASSERT(vol);
797     AFP_ASSERT(dir);
798     AFP_ASSERT(path);
799     AFP_ASSERT(len > 0);
800
801     if ((cdir = dircache_search_by_name(vol, dir, path->u_name, strlen(path->u_name), path->st.st_ctime)) != NULL) {
802         /* there's a stray entry in the dircache */
803         LOG(log_debug, logtype_afpd, "dir_add(did:%u,'%s/%s'): {stray cache entry: did:%u,'%s', removing}",
804             ntohl(dir->d_did), cfrombstr(dir->d_fullpath), path->u_name,
805             ntohl(cdir->d_did), cfrombstr(dir->d_fullpath));
806         if (dir_remove(vol, cdir) != 0) {
807             dircache_dump();
808             AFP_PANIC("dir_add");
809         }
810     }
811
812     /* get_id needs adp for reading CNID from adouble file */
813     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
814     if ((ad_open_metadata(path->u_name, ADFLAGS_DIR, 0, &ad)) == 0) /* 1 */
815         adp = &ad;
816
817     /* Get CNID */
818     if ((id = get_id(vol, adp, &path->st, dir->d_did, path->u_name, len)) == 0) { /* 2 */
819         err = 1;
820         goto exit;
821     }
822
823     if (adp)
824         ad_close_metadata(adp);
825
826     /* Get macname from unixname */
827     if (path->m_name == NULL) {
828         if ((path->m_name = utompath(vol, path->u_name, id, utf8_encoding())) == NULL) {
829             err = 2;
830             goto exit;
831         }
832     }
833
834     /* Build fullpath */
835     if ( ((fullpath = bstrcpy(dir->d_fullpath)) == NULL) /* 3 */
836          || (bconchar(fullpath, '/') != BSTR_OK)
837          || (bcatcstr(fullpath, path->u_name)) != BSTR_OK) {
838         LOG(log_error, logtype_afpd, "dir_add: fullpath: %s", strerror(errno) );
839         err = 3;
840         goto exit;
841     }
842
843     /* Allocate and initialize struct dir */
844     if ((cdir = dir_new( path->m_name, path->u_name, vol, dir->d_did, id, fullpath, path->st.st_ctime)) == NULL) { /* 3 */
845         err = 4;
846         goto exit;
847     }
848
849     if ((dircache_add(vol, cdir)) != 0) { /* 4 */
850         LOG(log_error, logtype_afpd, "dir_add: fatal dircache error: %s", cfrombstr(fullpath));
851         exit(EXITERR_SYS);
852     }
853
854 exit:
855     if (err != 0) {
856         LOG(log_debug, logtype_afpd, "dir_add('%s/%s'): error: %u",
857             cfrombstr(dir->d_u_name), path->u_name, err);
858
859         if (adp)
860             ad_close_metadata(adp);
861         if (!cdir && fullpath)
862             bdestroy(fullpath);
863         if (cdir)
864             dir_free(cdir);
865         cdir = NULL;
866     } else {
867         /* no error */
868         LOG(log_debug, logtype_afpd, "dir_add(did:%u,'%s/%s'): {cached: %u,'%s'}",
869             ntohl(dir->d_did), cfrombstr(dir->d_fullpath), path->u_name,
870             ntohl(cdir->d_did), cfrombstr(cdir->d_fullpath));
871     }
872
873     return(cdir);
874 }
875
876 /*!
877  * Free the queue with invalid struct dirs
878  *
879  * This gets called at the end of every AFP func.
880  */
881 void dir_free_invalid_q(void)
882 {
883     struct dir *dir;
884     while (dir = (struct dir *)dequeue(invalid_dircache_entries))
885         dir_free(dir);
886 }
887
888 /*!
889  * @brief Remove a dir from a cache and queue it for freeing
890  *
891  * 1. Check if the dir is locked or has opened forks
892  * 2. Remove it from the cache
893  * 3. Queue it for removal
894  * 4. If it's a request to remove curdir, use dirlookup to get a fresh dir for the did
895  * 5. Mark it as invalid
896  *
897  * @param (r) pointer to struct vol
898  * @param (rw) pointer to struct dir
899  */
900 int dir_remove(const struct vol *vol, struct dir *dir)
901 {
902     AFP_ASSERT(vol);
903     AFP_ASSERT(dir);
904
905     if (dir->d_did == DIRDID_ROOT_PARENT || dir->d_did == DIRDID_ROOT)
906         return 0;
907
908     if (dir->d_flags & DIRF_CACHELOCK) { /* 1 */
909         LOG(log_warning, logtype_afpd, "dir_remove(did:%u,'%s'): dir is locked",
910             ntohl(dir->d_did), cfrombstr(dir->d_u_name));
911         return 0;
912     }
913
914     LOG(log_debug, logtype_afpd, "dir_remove(did:%u,'%s'): {removing}",
915         ntohl(dir->d_did), cfrombstr(dir->d_u_name));
916
917     dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX); /* 2 */
918     enqueue(invalid_dircache_entries, dir); /* 3 */
919
920     if (curdir == dir) {        /* 4 */
921         curdir = dirlookup(vol, dir->d_did);
922         if (movecwd(vol, curdir) < 0) {
923             LOG(log_error, logtype_afpd, "dir_remove: can't chdir to : %s",
924                 cfrombstr(curdir->d_fullpath));
925         }
926     }
927
928     dir->d_did = CNID_INVALID;              /* 5 */
929
930     return 0;
931 }
932
933 #if 0 /* unused */
934 /*!
935  * @brief Modify a struct dir, adjust cache
936  *
937  * Any value that is 0 or NULL is not changed. If new_uname is NULL it is set to new_mname.
938  * If given new_uname == new_mname, new_uname will point to new_mname.
939  *
940  * @param vol       (r) pointer to struct vol
941  * @param dir       (rw) pointer to struct dir
942  * @param pdid      (r) new parent DID
943  * @param did       (r) new DID
944  * @param new_mname (r) new mac-name
945  * @param new_uname (r) new unix-name
946  * @param pdir_fullpath (r) new fullpath of parent dir
947  */
948 int dir_modify(const struct vol *vol,
949                struct dir *dir,
950                cnid_t pdid,
951                cnid_t did,
952                const char *new_mname,
953                const char *new_uname,
954                bstring pdir_fullpath)
955 {
956     int ret = 0;
957
958     /* Remove it from the cache */
959     dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX);
960
961     if (pdid)
962         dir->d_pdid = pdid;
963     if (did)
964         dir->d_did = did;
965
966     if (new_mname) {
967         /* free uname if it's not the same as mname */
968         if (dir->d_m_name != dir->d_u_name)
969             bdestroy(dir->d_u_name);
970
971         if (new_uname == NULL)
972             new_uname = new_mname;
973
974         /* assign new name */
975         if ((bassigncstr(dir->d_m_name, new_mname)) != BSTR_OK) {
976             LOG(log_error, logtype_afpd, "dir_modify: bassigncstr: %s", strerror(errno) );
977             return -1;
978         }
979
980         if (new_mname == new_uname || (strcmp(new_mname, new_uname) == 0)) {
981             dir->d_u_name = dir->d_m_name;
982         } else {
983             if ((dir->d_u_name = bfromcstr(new_uname)) == NULL) {
984                 LOG(log_error, logtype_afpd, "dir_modify: bassigncstr: %s", strerror(errno) );
985                 return -1;
986             }
987         }
988     }
989
990     if (pdir_fullpath) {
991         if (bassign(dir->d_fullpath, pdir_fullpath) != BSTR_OK)
992             return -1;
993         if (bcatcstr(dir->d_fullpath, "/") != BSTR_OK)
994             return -1;
995         if (bcatcstr(dir->d_fullpath, new_uname) != BSTR_OK)
996             return -1;
997     }
998
999     if (dir->d_m_name_ucs2)
1000         free(dir->d_m_name_ucs2);
1001     if ((size_t)-1 == convert_string_allocate((utf8_encoding())?CH_UTF8_MAC:vol->v_maccharset, CH_UCS2, dir->d_m_name, -1, (char**)&dir->d_m_name_ucs2))
1002         dir->d_m_name_ucs2 = NULL;
1003
1004     /* Re-add it to the cache */
1005     if ((dircache_add(vol, dir)) != 0) {
1006         dircache_dump();
1007         AFP_PANIC("dir_modify");
1008     }
1009
1010     return ret;
1011 }
1012 #endif
1013
1014 /*!
1015  * @brief Resolve a catalog node name path
1016  *
1017  * 1. Evaluate path type
1018  * 2. Move to start dir, if we cant, it might eg because of EACCES, build
1019  *    path from dirname, so eg getdirparams has sth it can chew on. curdir
1020  *    is dir parent then. All this is done in path_from_dir().
1021  * 3. Parse next cnode name in path, cases:
1022  * 4.   single "\0" -> do nothing
1023  * 5.   two or more consecutive "\0" -> chdir("..") one or more times
1024  * 6.   cnode name -> copy it to path.m_name
1025  * 7. Get unix name from mac name
1026  * 8. Special handling of request with did 1
1027  * 9. stat the cnode name
1028  * 10. If it's not there, it's probably an afp_createfile|dir,
1029  *     return with curdir = dir parent, struct path = dirname
1030  * 11. If it's there and it's a file, it must should be the last element of the requested
1031  *     path. Return with curdir = cnode name parent dir, struct path = filename
1032  * 12. Treat symlinks like files, dont follow them
1033  * 13. If it's a dir:
1034  * 14. Search the dircache for it
1035  * 15. If it's not in the cache, create a struct dir for it and add it to the cache
1036  * 16. chdir into the dir and
1037  * 17. set m_name to the mac equivalent of "."
1038  * 18. goto 3
1039  */
1040 struct path *cname(struct vol *vol, struct dir *dir, char **cpath)
1041 {
1042     static char        path[ MAXPATHLEN + 1];
1043     static struct path ret;
1044
1045     struct dir  *cdir;
1046     char        *data, *p;
1047     int         len;
1048     u_int32_t   hint;
1049     u_int16_t   len16;
1050     int         size = 0;
1051     int         toUTF8 = 0;
1052
1053     LOG(log_maxdebug, logtype_afpd, "came('%s'): {start}", cfrombstr(dir->d_fullpath));
1054
1055     data = *cpath;
1056     afp_errno = AFPERR_NOOBJ;
1057     memset(&ret, 0, sizeof(ret));
1058
1059     switch (ret.m_type = *data) { /* 1 */
1060     case 2:
1061         data++;
1062         len = (unsigned char) *data++;
1063         size = 2;
1064         if (afp_version >= 30) {
1065             ret.m_type = 3;
1066             toUTF8 = 1;
1067         }
1068         break;
1069     case 3:
1070         if (afp_version >= 30) {
1071             data++;
1072             memcpy(&hint, data, sizeof(hint));
1073             hint = ntohl(hint);
1074             data += sizeof(hint);
1075
1076             memcpy(&len16, data, sizeof(len16));
1077             len = ntohs(len16);
1078             data += 2;
1079             size = 7;
1080             break;
1081         }
1082         /* else it's an error */
1083     default:
1084         afp_errno = AFPERR_PARAM;
1085         return( NULL );
1086     }
1087     *cpath += len + size;
1088
1089     path[0] = 0;
1090     ret.m_name = path;
1091
1092     if (movecwd(vol, dir) < 0 ) {
1093         LOG(log_debug, logtype_afpd, "cname(did:%u): failed to chdir to '%s'",
1094             ntohl(dir->d_did), cfrombstr(dir->d_fullpath));
1095         if (len == 0)
1096             return path_from_dir(vol, dir, &ret);
1097         else
1098             return NULL;
1099     }
1100
1101     while (len) {         /* 3 */
1102         if (*data == 0) { /* 4 or 5 */
1103             data++;
1104             len--;
1105             while (len > 0 && *data == 0) { /* 5 */
1106                 /* chdir to parrent dir */
1107                 if ((dir = dirlookup(vol, dir->d_pdid)) == NULL)
1108                     return NULL;
1109                 if (movecwd( vol, dir ) < 0 ) {
1110                     dir_remove(vol, dir);
1111                     return NULL;
1112                 }
1113                 data++;
1114                 len--;
1115             }
1116             continue;
1117         }
1118
1119         /* 6*/
1120         for ( p = path; *data != 0 && len > 0; len-- ) {
1121             *p++ = *data++;
1122             if (p > &path[UTF8FILELEN_EARLY]) {   /* FIXME safeguard, limit of early Mac OS X */
1123                 afp_errno = AFPERR_PARAM;
1124                 return NULL;
1125             }
1126         }
1127         *p = 0;            /* Terminate string */
1128         ret.u_name = NULL;
1129
1130         if (cname_mtouname(vol, dir, &ret, toUTF8) != 0) { /* 7 */
1131             LOG(log_error, logtype_afpd, "cname('%s'): error from cname_mtouname", path);
1132             return NULL;
1133         }
1134
1135         LOG(log_maxdebug, logtype_afpd, "came('%s'): {node: '%s}", cfrombstr(dir->d_fullpath), ret.u_name);
1136
1137         /* Prevent access to our special folders like .AppleDouble */
1138         if (check_name(vol, ret.u_name)) {
1139             /* the name is illegal */
1140             LOG(log_info, logtype_afpd, "cname: illegal path: '%s'", ret.u_name);
1141             afp_errno = AFPERR_PARAM;
1142             return NULL;
1143         }
1144
1145         if (dir->d_did == DIRDID_ROOT_PARENT) { /* 8 */
1146             /*
1147              * Special case: CNID 1
1148              * root parent (did 1) has one child: the volume. Requests for did=1 with
1149              * some <name> must check against the volume name.
1150              */
1151             if ((strcmp(cfrombstr(vol->v_root->d_m_name), ret.m_name)) == 0)
1152                 cdir = vol->v_root;
1153             else
1154                 return NULL;
1155         } else {
1156             /*
1157              * CNID != 1, eg. most of the times we take this way.
1158              * Now check if current path-part is a file or dir:
1159              * o if it's dir we have to step into it
1160              * o if it's a file we expect it to be the last part of the requested path
1161              *   and thus call continue which should terminate the while loop because
1162              *   len = 0. Ok?
1163              */
1164             if (of_stat(&ret) != 0) { /* 9 */
1165                 /*
1166                  * ret.u_name doesn't exist, might be afp_createfile|dir
1167                  * that means it should have been the last part
1168                  */
1169                 if (len > 0) {
1170                     /* it wasn't the last part, so we have a bogus path request */
1171                     afp_errno = AFPERR_NOOBJ;
1172                     return NULL;
1173                 }
1174                 /*
1175                  * this will terminate clean in while (1) because len == 0,
1176                  * probably afp_createfile|dir
1177                  */
1178                 LOG(log_maxdebug, logtype_afpd, "came('%s'): {leave-cnode ENOENT (possile create request): '%s'}",
1179                     cfrombstr(dir->d_fullpath), ret.u_name);
1180                 continue; /* 10 */
1181             }
1182
1183             switch (ret.st.st_mode & S_IFMT) {
1184             case S_IFREG: /* 11 */
1185                 LOG(log_debug, logtype_afpd, "came('%s'): {file: '%s'}",
1186                     cfrombstr(dir->d_fullpath), ret.u_name);
1187                 if (len > 0) {
1188                     /* it wasn't the last part, so we have a bogus path request */
1189                     afp_errno = AFPERR_PARAM;
1190                     return NULL;
1191                 }
1192                 continue; /* continues while loop */
1193             case S_IFLNK: /* 12 */
1194                 LOG(log_debug, logtype_afpd, "came('%s'): {link: '%s'}",
1195                     cfrombstr(dir->d_fullpath), ret.u_name);
1196                 if (len > 0) {
1197                     LOG(log_warning, logtype_afpd, "came('%s'): {symlinked dir: '%s'}",
1198                         cfrombstr(dir->d_fullpath), ret.u_name);
1199                     afp_errno = AFPERR_PARAM;
1200                     return NULL;
1201                 }
1202                 continue; /* continues while loop */
1203             case S_IFDIR: /* 13 */
1204                 break;
1205             default:
1206                 LOG(log_info, logtype_afpd, "cname: special file: '%s'", ret.u_name);
1207                 afp_errno = AFPERR_NODIR;
1208                 return NULL;
1209             }
1210
1211             /* Search the cache */
1212             int unamelen = strlen(ret.u_name);
1213             cdir = dircache_search_by_name(vol, dir, ret.u_name, unamelen, ret.st.st_ctime); /* 14 */
1214             if (cdir == NULL) {
1215                 /* Not in cache, create one */
1216                 if ((cdir = dir_add(vol, dir, &ret, unamelen)) == NULL) { /* 15 */
1217                     LOG(log_error, logtype_afpd, "cname(did:%u, name:'%s', cwd:'%s'): failed to add dir",
1218                         ntohl(dir->d_did), ret.u_name, getcwdpath());
1219                     return NULL;
1220                 }
1221             }
1222         } /* if/else cnid==1 */
1223
1224         /* Now chdir to the evaluated dir */
1225         if (movecwd( vol, cdir ) < 0 ) { /* 16 */
1226             LOG(log_debug, logtype_afpd, "cname(cwd:'%s'): failed to chdir to new subdir '%s': %s",
1227                 cfrombstr(curdir->d_fullpath), cfrombstr(cdir->d_fullpath), strerror(errno));
1228             if (len == 0)
1229                 return path_from_dir(vol, cdir, &ret);
1230             else
1231                 return NULL;
1232         }
1233         dir = cdir;
1234         ret.m_name[0] = 0;      /* 17, so we later know last token was a dir */
1235     } /* while (len) */
1236
1237     if (curdir->d_did == DIRDID_ROOT_PARENT) {
1238         afp_errno = AFPERR_DID1;
1239         return NULL;
1240     }
1241
1242     if (ret.m_name[0] == 0) {
1243         /* Last part was a dir */
1244         ret.u_name = mtoupath(vol, ret.m_name, 0, 1); /* Force "." into a useable static buffer */
1245         ret.d_dir = dir;
1246     }
1247
1248     LOG(log_debug, logtype_afpd, "came('%s') {end: curdir:'%s', path:'%s'}",
1249         cfrombstr(dir->d_fullpath),
1250         cfrombstr(curdir->d_fullpath),
1251         ret.u_name);
1252
1253     return &ret;
1254 }
1255
1256 /*
1257  * @brief chdir() to dir
1258  *
1259  * @param vol   (r) pointer to struct vol
1260  * @param dir   (r) pointer to struct dir
1261  *
1262  * @returns 0 on success, -1 on error with afp_errno set appropiately
1263  */
1264 int movecwd(const struct vol *vol, struct dir *dir)
1265 {
1266     int ret;
1267
1268     AFP_ASSERT(vol);
1269     AFP_ASSERT(dir);
1270
1271     LOG(log_maxdebug, logtype_afpd, "movecwd: from: curdir:\"%s\", cwd:\"%s\"",
1272         cfrombstr(curdir->d_fullpath), getcwdpath());
1273
1274     if ( dir == curdir)
1275         return( 0 );
1276     if (dir->d_did == DIRDID_ROOT_PARENT) {
1277         curdir = &rootParent;
1278         return 0;
1279     }
1280
1281     LOG(log_debug, logtype_afpd, "movecwd(to: did: %u, \"%s\")",
1282         ntohl(dir->d_did), cfrombstr(dir->d_fullpath));
1283
1284     if ((ret = lchdir(cfrombstr(dir->d_fullpath))) != 0 ) {
1285         LOG(log_debug, logtype_afpd, "movecwd(\"%s\"): ret: %u, %s",
1286             cfrombstr(dir->d_fullpath), ret, strerror(errno));
1287         if (ret == 1) {
1288             /* p is a symlink or getcwd failed */
1289             afp_errno = AFPERR_BADTYPE;
1290
1291             if (chdir(vol->v_path ) < 0) {
1292                 LOG(log_error, logtype_afpd, "can't chdir back'%s': %s", vol->v_path, strerror(errno));
1293                 /* XXX what do we do here? */
1294             }
1295             curdir = vol->v_root;
1296             return -1;
1297         }
1298
1299         switch (errno) {
1300         case EACCES:
1301         case EPERM:
1302             afp_errno = AFPERR_ACCESS;
1303             break;
1304         default:
1305             afp_errno = AFPERR_NOOBJ;
1306         }
1307         return( -1 );
1308     }
1309
1310     curdir = dir;
1311     return( 0 );
1312 }
1313
1314 /*
1315  * We can't use unix file's perm to support Apple's inherited protection modes.
1316  * If we aren't the file's owner we can't change its perms when moving it and smb
1317  * nfs,... don't even try.
1318  */
1319 #define AFP_CHECK_ACCESS
1320
1321 int check_access(char *path, int mode)
1322 {
1323 #ifdef AFP_CHECK_ACCESS
1324     struct maccess ma;
1325     char *p;
1326
1327     p = ad_dir(path);
1328     if (!p)
1329         return -1;
1330
1331     accessmode(p, &ma, curdir, NULL);
1332     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE))
1333         return -1;
1334     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD))
1335         return -1;
1336 #endif
1337     return 0;
1338 }
1339
1340 /* --------------------- */
1341 int file_access(struct path *path, int mode)
1342 {
1343     struct maccess ma;
1344
1345     accessmode(path->u_name, &ma, curdir, &path->st);
1346
1347     LOG(log_debug, logtype_afpd, "file_access(\"%s\"): mapped user mode: 0x%02x",
1348         path->u_name, ma.ma_user);
1349
1350     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE)) {
1351         LOG(log_debug, logtype_afpd, "file_access(\"%s\"): write access denied", path->u_name);
1352         return -1;
1353     }
1354     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD)) {
1355         LOG(log_debug, logtype_afpd, "file_access(\"%s\"): read access denied", path->u_name);
1356         return -1;
1357     }
1358     return 0;
1359
1360 }
1361
1362 /* --------------------- */
1363 void setdiroffcnt(struct dir *dir, struct stat *st,  u_int32_t count)
1364 {
1365     dir->offcnt = count;
1366     dir->ctime = st->st_ctime;
1367     dir->d_flags &= ~DIRF_CNID;
1368 }
1369
1370
1371 /* ---------------------
1372  * is our cached also for reenumerate id?
1373  */
1374 int dirreenumerate(struct dir *dir, struct stat *st)
1375 {
1376     return st->st_ctime == dir->ctime && (dir->d_flags & DIRF_CNID);
1377 }
1378
1379 /* ------------------------------
1380    (".", curdir)
1381    (name, dir) with curdir:name == dir, from afp_enumerate
1382 */
1383
1384 int getdirparams(const struct vol *vol,
1385                  u_int16_t bitmap, struct path *s_path,
1386                  struct dir *dir,
1387                  char *buf, size_t *buflen )
1388 {
1389     struct maccess  ma;
1390     struct adouble  ad;
1391     char        *data, *l_nameoff = NULL, *utf_nameoff = NULL;
1392     int         bit = 0, isad = 0;
1393     u_int32_t           aint;
1394     u_int16_t       ashort;
1395     int                 ret;
1396     u_int32_t           utf8 = 0;
1397     cnid_t              pdid;
1398     struct stat *st = &s_path->st;
1399     char *upath = s_path->u_name;
1400
1401     if ((bitmap & ((1 << DIRPBIT_ATTR)  |
1402                    (1 << DIRPBIT_CDATE) |
1403                    (1 << DIRPBIT_MDATE) |
1404                    (1 << DIRPBIT_BDATE) |
1405                    (1 << DIRPBIT_FINFO)))) {
1406
1407         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1408         if ( !ad_metadata( upath, ADFLAGS_CREATE|ADFLAGS_DIR, &ad) ) {
1409             isad = 1;
1410             if (ad.ad_md->adf_flags & O_CREAT) {
1411                 /* We just created it */
1412                 ad_setname(&ad, s_path->m_name);
1413                 ad_setid( &ad,
1414                           s_path->st.st_dev,
1415                           s_path->st.st_ino,
1416                           dir->d_did,
1417                           dir->d_pdid,
1418                           vol->v_stamp);
1419                 ad_flush( &ad);
1420             }
1421         }
1422     }
1423
1424     pdid = dir->d_pdid;
1425
1426     data = buf;
1427     while ( bitmap != 0 ) {
1428         while (( bitmap & 1 ) == 0 ) {
1429             bitmap = bitmap>>1;
1430             bit++;
1431         }
1432
1433         switch ( bit ) {
1434         case DIRPBIT_ATTR :
1435             if ( isad ) {
1436                 ad_getattr(&ad, &ashort);
1437             } else if (invisible_dots(vol, cfrombstr(dir->d_u_name))) {
1438                 ashort = htons(ATTRBIT_INVISIBLE);
1439             } else
1440                 ashort = 0;
1441             ashort |= htons(ATTRBIT_SHARED);
1442             memcpy( data, &ashort, sizeof( ashort ));
1443             data += sizeof( ashort );
1444             break;
1445
1446         case DIRPBIT_PDID :
1447             memcpy( data, &pdid, sizeof( pdid ));
1448             data += sizeof( pdid );
1449             LOG(log_debug, logtype_afpd, "metadata('%s'):     Parent DID: %u",
1450                 s_path->u_name, ntohl(pdid));
1451             break;
1452
1453         case DIRPBIT_CDATE :
1454             if (!isad || (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0))
1455                 aint = AD_DATE_FROM_UNIX(st->st_mtime);
1456             memcpy( data, &aint, sizeof( aint ));
1457             data += sizeof( aint );
1458             break;
1459
1460         case DIRPBIT_MDATE :
1461             aint = AD_DATE_FROM_UNIX(st->st_mtime);
1462             memcpy( data, &aint, sizeof( aint ));
1463             data += sizeof( aint );
1464             break;
1465
1466         case DIRPBIT_BDATE :
1467             if (!isad || (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1468                 aint = AD_DATE_START;
1469             memcpy( data, &aint, sizeof( aint ));
1470             data += sizeof( aint );
1471             break;
1472
1473         case DIRPBIT_FINFO :
1474             if ( isad ) {
1475                 memcpy( data, ad_entry( &ad, ADEID_FINDERI ), 32 );
1476             } else { /* no appledouble */
1477                 memset( data, 0, 32 );
1478                 /* set default view -- this also gets done in ad_open() */
1479                 ashort = htons(FINDERINFO_CLOSEDVIEW);
1480                 memcpy(data + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
1481
1482                 /* dot files are by default visible */
1483                 if (invisible_dots(vol, cfrombstr(dir->d_u_name))) {
1484                     ashort = htons(FINDERINFO_INVISIBLE);
1485                     memcpy(data + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
1486                 }
1487             }
1488             data += 32;
1489             break;
1490
1491         case DIRPBIT_LNAME :
1492             if (dir->d_m_name) /* root of parent can have a null name */
1493                 l_nameoff = data;
1494             else
1495                 memset(data, 0, sizeof(u_int16_t));
1496             data += sizeof( u_int16_t );
1497             break;
1498
1499         case DIRPBIT_SNAME :
1500             memset(data, 0, sizeof(u_int16_t));
1501             data += sizeof( u_int16_t );
1502             break;
1503
1504         case DIRPBIT_DID :
1505             memcpy( data, &dir->d_did, sizeof( aint ));
1506             data += sizeof( aint );
1507             LOG(log_debug, logtype_afpd, "metadata('%s'):            DID: %u",
1508                 s_path->u_name, ntohl(dir->d_did));
1509             break;
1510
1511         case DIRPBIT_OFFCNT :
1512             ashort = 0;
1513             /* this needs to handle current directory access rights */
1514             if (diroffcnt(dir, st)) {
1515                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1516             }
1517             else if ((ret = for_each_dirent(vol, upath, NULL,NULL)) >= 0) {
1518                 setdiroffcnt(dir, st,  ret);
1519                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1520             }
1521             ashort = htons( ashort );
1522             memcpy( data, &ashort, sizeof( ashort ));
1523             data += sizeof( ashort );
1524             break;
1525
1526         case DIRPBIT_UID :
1527             aint = htonl(st->st_uid);
1528             memcpy( data, &aint, sizeof( aint ));
1529             data += sizeof( aint );
1530             break;
1531
1532         case DIRPBIT_GID :
1533             aint = htonl(st->st_gid);
1534             memcpy( data, &aint, sizeof( aint ));
1535             data += sizeof( aint );
1536             break;
1537
1538         case DIRPBIT_ACCESS :
1539             accessmode( upath, &ma, dir , st);
1540
1541             *data++ = ma.ma_user;
1542             *data++ = ma.ma_world;
1543             *data++ = ma.ma_group;
1544             *data++ = ma.ma_owner;
1545             break;
1546
1547             /* Client has requested the ProDOS information block.
1548                Just pass back the same basic block for all
1549                directories. <shirsch@ibm.net> */
1550         case DIRPBIT_PDINFO :
1551             if (afp_version >= 30) { /* UTF8 name */
1552                 utf8 = kTextEncodingUTF8;
1553                 if (dir->d_m_name) /* root of parent can have a null name */
1554                     utf_nameoff = data;
1555                 else
1556                     memset(data, 0, sizeof(u_int16_t));
1557                 data += sizeof( u_int16_t );
1558                 aint = 0;
1559                 memcpy(data, &aint, sizeof( aint ));
1560                 data += sizeof( aint );
1561             }
1562             else { /* ProDOS Info Block */
1563                 *data++ = 0x0f;
1564                 *data++ = 0;
1565                 ashort = htons( 0x0200 );
1566                 memcpy( data, &ashort, sizeof( ashort ));
1567                 data += sizeof( ashort );
1568                 memset( data, 0, sizeof( ashort ));
1569                 data += sizeof( ashort );
1570             }
1571             break;
1572
1573         case DIRPBIT_UNIXPR :
1574             aint = htonl(st->st_uid);
1575             memcpy( data, &aint, sizeof( aint ));
1576             data += sizeof( aint );
1577             aint = htonl(st->st_gid);
1578             memcpy( data, &aint, sizeof( aint ));
1579             data += sizeof( aint );
1580
1581             aint = st->st_mode;
1582             aint = htonl ( aint & ~S_ISGID );  /* Remove SGID, OSX doesn't like it ... */
1583             memcpy( data, &aint, sizeof( aint ));
1584             data += sizeof( aint );
1585
1586             accessmode( upath, &ma, dir , st);
1587
1588             *data++ = ma.ma_user;
1589             *data++ = ma.ma_world;
1590             *data++ = ma.ma_group;
1591             *data++ = ma.ma_owner;
1592             break;
1593
1594         default :
1595             if ( isad ) {
1596                 ad_close_metadata( &ad );
1597             }
1598             return( AFPERR_BITMAP );
1599         }
1600         bitmap = bitmap>>1;
1601         bit++;
1602     }
1603     if ( l_nameoff ) {
1604         ashort = htons( data - buf );
1605         memcpy( l_nameoff, &ashort, sizeof( ashort ));
1606         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, 0);
1607     }
1608     if ( utf_nameoff ) {
1609         ashort = htons( data - buf );
1610         memcpy( utf_nameoff, &ashort, sizeof( ashort ));
1611         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, utf8);
1612     }
1613     if ( isad ) {
1614         ad_close_metadata( &ad );
1615     }
1616     *buflen = data - buf;
1617     return( AFP_OK );
1618 }
1619
1620 /* ----------------------------- */
1621 int path_error(struct path *path, int error)
1622 {
1623 /* - a dir with access error
1624  * - no error it's a file
1625  * - file not found
1626  */
1627     if (path_isadir(path))
1628         return afp_errno;
1629     if (path->st_valid && path->st_errno)
1630         return error;
1631     return AFPERR_BADTYPE ;
1632 }
1633
1634 /* ----------------------------- */
1635 int afp_setdirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
1636 {
1637     struct vol  *vol;
1638     struct dir  *dir;
1639     struct path *path;
1640     u_int16_t   vid, bitmap;
1641     u_int32_t   did;
1642     int     rc;
1643
1644     *rbuflen = 0;
1645     ibuf += 2;
1646     memcpy( &vid, ibuf, sizeof( vid ));
1647     ibuf += sizeof( vid );
1648
1649     if (NULL == ( vol = getvolbyvid( vid )) ) {
1650         return( AFPERR_PARAM );
1651     }
1652
1653     if (vol->v_flags & AFPVOL_RO)
1654         return AFPERR_VLOCK;
1655
1656     memcpy( &did, ibuf, sizeof( did ));
1657     ibuf += sizeof( int );
1658
1659     if (NULL == ( dir = dirlookup( vol, did )) ) {
1660         return afp_errno;
1661     }
1662
1663     memcpy( &bitmap, ibuf, sizeof( bitmap ));
1664     bitmap = ntohs( bitmap );
1665     ibuf += sizeof( bitmap );
1666
1667     if (NULL == ( path = cname( vol, dir, &ibuf )) ) {
1668         return get_afp_errno(AFPERR_NOOBJ);
1669     }
1670
1671     if ( *path->m_name != '\0' ) {
1672         rc = path_error(path, AFPERR_NOOBJ);
1673         /* maybe we are trying to set perms back */
1674         if (rc != AFPERR_ACCESS)
1675             return rc;
1676     }
1677
1678     /*
1679      * If ibuf is odd, make it even.
1680      */
1681     if ((u_long)ibuf & 1 ) {
1682         ibuf++;
1683     }
1684
1685     if (AFP_OK == ( rc = setdirparams(vol, path, bitmap, ibuf )) ) {
1686         setvoltime(obj, vol );
1687     }
1688     return( rc );
1689 }
1690
1691 /*
1692  * cf AFP3.0.pdf page 244 for change_mdate and change_parent_mdate logic
1693  *
1694  * assume path == '\0' eg. it's a directory in canonical form
1695  */
1696 int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *buf )
1697 {
1698     struct maccess  ma;
1699     struct adouble  ad;
1700     struct utimbuf      ut;
1701     struct timeval      tv;
1702
1703     char                *upath;
1704     struct dir          *dir;
1705     int         bit, isad = 1;
1706     int                 cdate, bdate;
1707     int                 owner, group;
1708     u_int16_t       ashort, bshort, oshort;
1709     int                 err = AFP_OK;
1710     int                 change_mdate = 0;
1711     int                 change_parent_mdate = 0;
1712     int                 newdate = 0;
1713     u_int16_t           bitmap = d_bitmap;
1714     u_char              finder_buf[32];
1715     u_int32_t       upriv;
1716     mode_t              mpriv = 0;
1717     u_int16_t           upriv_bit = 0;
1718
1719     bit = 0;
1720     upath = path->u_name;
1721     dir   = path->d_dir;
1722     while ( bitmap != 0 ) {
1723         while (( bitmap & 1 ) == 0 ) {
1724             bitmap = bitmap>>1;
1725             bit++;
1726         }
1727
1728         switch( bit ) {
1729         case DIRPBIT_ATTR :
1730             change_mdate = 1;
1731             memcpy( &ashort, buf, sizeof( ashort ));
1732             buf += sizeof( ashort );
1733             break;
1734         case DIRPBIT_CDATE :
1735             change_mdate = 1;
1736             memcpy(&cdate, buf, sizeof(cdate));
1737             buf += sizeof( cdate );
1738             break;
1739         case DIRPBIT_MDATE :
1740             memcpy(&newdate, buf, sizeof(newdate));
1741             buf += sizeof( newdate );
1742             break;
1743         case DIRPBIT_BDATE :
1744             change_mdate = 1;
1745             memcpy(&bdate, buf, sizeof(bdate));
1746             buf += sizeof( bdate );
1747             break;
1748         case DIRPBIT_FINFO :
1749             change_mdate = 1;
1750             memcpy( finder_buf, buf, 32 );
1751             buf += 32;
1752             break;
1753         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1754             change_parent_mdate = 1;
1755             memcpy( &owner, buf, sizeof(owner));
1756             buf += sizeof( owner );
1757             break;
1758         case DIRPBIT_GID :
1759             change_parent_mdate = 1;
1760             memcpy( &group, buf, sizeof( group ));
1761             buf += sizeof( group );
1762             break;
1763         case DIRPBIT_ACCESS :
1764             change_mdate = 1;
1765             change_parent_mdate = 1;
1766             ma.ma_user = *buf++;
1767             ma.ma_world = *buf++;
1768             ma.ma_group = *buf++;
1769             ma.ma_owner = *buf++;
1770             mpriv = mtoumode( &ma ) | vol->v_dperm;
1771             if (dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1772                 err = set_dir_errors(path, "setdirmode", errno);
1773                 bitmap = 0;
1774             }
1775             break;
1776             /* Ignore what the client thinks we should do to the
1777                ProDOS information block.  Skip over the data and
1778                report nothing amiss. <shirsch@ibm.net> */
1779         case DIRPBIT_PDINFO :
1780             if (afp_version < 30) {
1781                 buf += 6;
1782             }
1783             else {
1784                 err = AFPERR_BITMAP;
1785                 bitmap = 0;
1786             }
1787             break;
1788         case DIRPBIT_UNIXPR :
1789             if (vol_unix_priv(vol)) {
1790                 memcpy( &owner, buf, sizeof(owner)); /* FIXME need to change owner too? */
1791                 buf += sizeof( owner );
1792                 memcpy( &group, buf, sizeof( group ));
1793                 buf += sizeof( group );
1794
1795                 change_mdate = 1;
1796                 change_parent_mdate = 1;
1797                 memcpy( &upriv, buf, sizeof( upriv ));
1798                 buf += sizeof( upriv );
1799                 upriv = ntohl (upriv) | vol->v_dperm;
1800                 if (dir_rx_set(upriv)) {
1801                     /* maybe we are trying to set perms back */
1802                     if ( setdirunixmode(vol, upath, upriv) < 0 ) {
1803                         bitmap = 0;
1804                         err = set_dir_errors(path, "setdirunixmode", errno);
1805                     }
1806                 }
1807                 else {
1808                     /* do it later */
1809                     upriv_bit = 1;
1810                 }
1811                 break;
1812             }
1813             /* fall through */
1814         default :
1815             err = AFPERR_BITMAP;
1816             bitmap = 0;
1817             break;
1818         }
1819
1820         bitmap = bitmap>>1;
1821         bit++;
1822     }
1823     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1824
1825     if (ad_open_metadata( upath, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
1826         /*
1827          * Check to see what we're trying to set.  If it's anything
1828          * but ACCESS, UID, or GID, give an error.  If it's any of those
1829          * three, we don't need the ad to be open, so just continue.
1830          *
1831          * note: we also don't need to worry about mdate. also, be quiet
1832          *       if we're using the noadouble option.
1833          */
1834         if (!vol_noadouble(vol) && (d_bitmap &
1835                                     ~((1<<DIRPBIT_ACCESS)|(1<<DIRPBIT_UNIXPR)|
1836                                       (1<<DIRPBIT_UID)|(1<<DIRPBIT_GID)|
1837                                       (1<<DIRPBIT_MDATE)|(1<<DIRPBIT_PDINFO)))) {
1838             return AFPERR_ACCESS;
1839         }
1840
1841         isad = 0;
1842     } else {
1843         /*
1844          * Check to see if a create was necessary. If it was, we'll want
1845          * to set our name, etc.
1846          */
1847         if ( (ad_get_HF_flags( &ad ) & O_CREAT)) {
1848             ad_setname(&ad, cfrombstr(curdir->d_m_name));
1849         }
1850     }
1851
1852     bit = 0;
1853     bitmap = d_bitmap;
1854     while ( bitmap != 0 ) {
1855         while (( bitmap & 1 ) == 0 ) {
1856             bitmap = bitmap>>1;
1857             bit++;
1858         }
1859
1860         switch( bit ) {
1861         case DIRPBIT_ATTR :
1862             if (isad) {
1863                 ad_getattr(&ad, &bshort);
1864                 oshort = bshort;
1865                 if ( ntohs( ashort ) & ATTRBIT_SETCLR ) {
1866                     bshort |= htons( ntohs( ashort ) & ~ATTRBIT_SETCLR );
1867                 } else {
1868                     bshort &= ~ashort;
1869                 }
1870                 if ((bshort & htons(ATTRBIT_INVISIBLE)) != (oshort & htons(ATTRBIT_INVISIBLE)))
1871                     change_parent_mdate = 1;
1872                 ad_setattr(&ad, bshort);
1873             }
1874             break;
1875         case DIRPBIT_CDATE :
1876             if (isad) {
1877                 ad_setdate(&ad, AD_DATE_CREATE, cdate);
1878             }
1879             break;
1880         case DIRPBIT_MDATE :
1881             break;
1882         case DIRPBIT_BDATE :
1883             if (isad) {
1884                 ad_setdate(&ad, AD_DATE_BACKUP, bdate);
1885             }
1886             break;
1887         case DIRPBIT_FINFO :
1888             if (isad) {
1889                 /* Fixes #2802236 */
1890                 u_int16_t *fflags = (u_int16_t *)(finder_buf + FINDERINFO_FRFLAGOFF);
1891                 *fflags &= htons(~FINDERINFO_ISHARED);
1892                 /* #2802236 end */
1893                 if (  dir->d_did == DIRDID_ROOT ) {
1894                     /*
1895                      * Alright, we admit it, this is *really* sick!
1896                      * The 4 bytes that we don't copy, when we're dealing
1897                      * with the root of a volume, are the directory's
1898                      * location information. This eliminates that annoying
1899                      * behavior one sees when mounting above another mount
1900                      * point.
1901                      */
1902                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 10 );
1903                     memcpy( ad_entry( &ad, ADEID_FINDERI ) + 14, finder_buf + 14, 18 );
1904                 } else {
1905                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 32 );
1906                 }
1907             }
1908             break;
1909         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1910             if ( (dir->d_did == DIRDID_ROOT) &&
1911                  (setdeskowner( ntohl(owner), -1 ) < 0)) {
1912                 err = set_dir_errors(path, "setdeskowner", errno);
1913                 if (isad && err == AFPERR_PARAM) {
1914                     err = AFP_OK; /* ???*/
1915                 }
1916                 else {
1917                     goto setdirparam_done;
1918                 }
1919             }
1920             if ( setdirowner(vol, upath, ntohl(owner), -1 ) < 0 ) {
1921                 err = set_dir_errors(path, "setdirowner", errno);
1922                 goto setdirparam_done;
1923             }
1924             break;
1925         case DIRPBIT_GID :
1926             if (dir->d_did == DIRDID_ROOT)
1927                 setdeskowner( -1, ntohl(group) );
1928             if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1929                 err = set_dir_errors(path, "setdirowner", errno);
1930                 goto setdirparam_done;
1931             }
1932             break;
1933         case DIRPBIT_ACCESS :
1934             if (dir->d_did == DIRDID_ROOT) {
1935                 setdeskmode(mpriv);
1936                 if (!dir_rx_set(mpriv)) {
1937                     /* we can't remove read and search for owner on volume root */
1938                     err = AFPERR_ACCESS;
1939                     goto setdirparam_done;
1940                 }
1941             }
1942
1943             if (!dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1944                 err = set_dir_errors(path, "setdirmode", errno);
1945                 goto setdirparam_done;
1946             }
1947             break;
1948         case DIRPBIT_PDINFO :
1949             if (afp_version >= 30) {
1950                 err = AFPERR_BITMAP;
1951                 goto setdirparam_done;
1952             }
1953             break;
1954         case DIRPBIT_UNIXPR :
1955             if (vol_unix_priv(vol)) {
1956                 if (dir->d_did == DIRDID_ROOT) {
1957                     if (!dir_rx_set(upriv)) {
1958                         /* we can't remove read and search for owner on volume root */
1959                         err = AFPERR_ACCESS;
1960                         goto setdirparam_done;
1961                     }
1962                     setdeskowner( -1, ntohl(group) );
1963                     setdeskmode( upriv );
1964                 }
1965                 if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1966                     err = set_dir_errors(path, "setdirowner", errno);
1967                     goto setdirparam_done;
1968                 }
1969
1970                 if ( upriv_bit && setdirunixmode(vol, upath, upriv) < 0 ) {
1971                     err = set_dir_errors(path, "setdirunixmode", errno);
1972                     goto setdirparam_done;
1973                 }
1974             }
1975             else {
1976                 err = AFPERR_BITMAP;
1977                 goto setdirparam_done;
1978             }
1979             break;
1980         default :
1981             err = AFPERR_BITMAP;
1982             goto setdirparam_done;
1983             break;
1984         }
1985
1986         bitmap = bitmap>>1;
1987         bit++;
1988     }
1989
1990 setdirparam_done:
1991     if (change_mdate && newdate == 0 && gettimeofday(&tv, NULL) == 0) {
1992         newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
1993     }
1994     if (newdate) {
1995         if (isad)
1996             ad_setdate(&ad, AD_DATE_MODIFY, newdate);
1997         ut.actime = ut.modtime = AD_DATE_TO_UNIX(newdate);
1998         utime(upath, &ut);
1999     }
2000
2001     if ( isad ) {
2002         if (path->st_valid && !path->st_errno) {
2003             struct stat *st = &path->st;
2004
2005             if (dir && dir->d_pdid) {
2006                 ad_setid(&ad, st->st_dev, st->st_ino,  dir->d_did, dir->d_pdid, vol->v_stamp);
2007             }
2008         }
2009         ad_flush( &ad);
2010         ad_close_metadata( &ad);
2011     }
2012
2013     if (change_parent_mdate && dir->d_did != DIRDID_ROOT
2014         && gettimeofday(&tv, NULL) == 0) {
2015         if (movecwd(vol, dirlookup(vol, dir->d_pdid)) == 0) {
2016             newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
2017             /* be careful with bitmap because now dir is null */
2018             bitmap = 1<<DIRPBIT_MDATE;
2019             setdirparams(vol, &Cur_Path, bitmap, (char *)&newdate);
2020             /* should we reset curdir ?*/
2021         }
2022     }
2023
2024     return err;
2025 }
2026
2027 int afp_syncdir(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2028 {
2029 #ifdef HAVE_DIRFD
2030     DIR                  *dp;
2031 #endif
2032     int                  dfd;
2033     struct vol           *vol;
2034     struct dir           *dir;
2035     u_int32_t            did;
2036     u_int16_t            vid;
2037
2038     *rbuflen = 0;
2039     ibuf += 2;
2040
2041     memcpy( &vid, ibuf, sizeof( vid ));
2042     ibuf += sizeof( vid );
2043     if (NULL == (vol = getvolbyvid( vid )) ) {
2044         return( AFPERR_PARAM );
2045     }
2046
2047     memcpy( &did, ibuf, sizeof( did ));
2048     ibuf += sizeof( did );
2049
2050     /*
2051      * Here's the deal:
2052      * if it's CNID 2 our only choice to meet the specs is call sync.
2053      * For any other CNID just sync that dir. To my knowledge the
2054      * intended use of FPSyncDir is to sync the volume so all we're
2055      * ever going to see here is probably CNID 2. Anyway, we' prepared.
2056      */
2057
2058     if ( ntohl(did) == 2 ) {
2059         sync();
2060     } else {
2061         if (NULL == ( dir = dirlookup( vol, did )) ) {
2062             return afp_errno; /* was AFPERR_NOOBJ */
2063         }
2064
2065         if (movecwd( vol, dir ) < 0 )
2066             return ( AFPERR_NOOBJ );
2067
2068         /*
2069          * Assuming only OSens that have dirfd also may require fsyncing directories
2070          * in order to flush metadata e.g. Linux.
2071          */
2072
2073 #ifdef HAVE_DIRFD
2074         if (NULL == ( dp = opendir( "." )) ) {
2075             switch( errno ) {
2076             case ENOENT :
2077                 return( AFPERR_NOOBJ );
2078             case EACCES :
2079                 return( AFPERR_ACCESS );
2080             default :
2081                 return( AFPERR_PARAM );
2082             }
2083         }
2084
2085         LOG(log_debug, logtype_afpd, "afp_syncdir: dir: '%s'", dir->d_u_name);
2086
2087         dfd = dirfd( dp );
2088         if ( fsync ( dfd ) < 0 )
2089             LOG(log_error, logtype_afpd, "afp_syncdir(%s):  %s",
2090                 dir->d_u_name, strerror(errno) );
2091         closedir(dp); /* closes dfd too */
2092 #endif
2093
2094         if ( -1 == (dfd = open(vol->ad_path(".", ADFLAGS_DIR), O_RDWR))) {
2095             switch( errno ) {
2096             case ENOENT:
2097                 return( AFPERR_NOOBJ );
2098             case EACCES:
2099                 return( AFPERR_ACCESS );
2100             default:
2101                 return( AFPERR_PARAM );
2102             }
2103         }
2104
2105         LOG(log_debug, logtype_afpd, "afp_syncdir: ad-file: '%s'",
2106             vol->ad_path(".", ADFLAGS_DIR) );
2107
2108         if ( fsync(dfd) < 0 )
2109             LOG(log_error, logtype_afpd, "afp_syncdir(%s): %s",
2110                 vol->ad_path(cfrombstr(dir->d_u_name), ADFLAGS_DIR), strerror(errno) );
2111         close(dfd);
2112     }
2113
2114     return ( AFP_OK );
2115 }
2116
2117 int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2118 {
2119     struct adouble  ad;
2120     struct vol      *vol;
2121     struct dir      *dir;
2122     char        *upath;
2123     struct path         *s_path;
2124     u_int32_t       did;
2125     u_int16_t       vid;
2126     int                 err;
2127
2128     *rbuflen = 0;
2129     ibuf += 2;
2130
2131     memcpy( &vid, ibuf, sizeof( vid ));
2132     ibuf += sizeof( vid );
2133     if (NULL == ( vol = getvolbyvid( vid )) ) {
2134         return( AFPERR_PARAM );
2135     }
2136
2137     if (vol->v_flags & AFPVOL_RO)
2138         return AFPERR_VLOCK;
2139
2140     memcpy( &did, ibuf, sizeof( did ));
2141     ibuf += sizeof( did );
2142     if (NULL == ( dir = dirlookup( vol, did )) ) {
2143         return afp_errno; /* was AFPERR_NOOBJ */
2144     }
2145     /* for concurrent access we need to be sure we are not in the
2146      * folder we want to create...
2147      */
2148     movecwd(vol, dir);
2149
2150     if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
2151         return get_afp_errno(AFPERR_PARAM);
2152     }
2153     /* cname was able to move curdir to it! */
2154     if (*s_path->m_name == '\0')
2155         return AFPERR_EXIST;
2156
2157     upath = s_path->u_name;
2158
2159     if (AFP_OK != (err = netatalk_mkdir(vol, upath))) {
2160         return err;
2161     }
2162
2163     if (of_stat(s_path) < 0) {
2164         return AFPERR_MISC;
2165     }
2166
2167     curdir->offcnt++;
2168
2169     if ((dir = dir_add(vol, curdir, s_path, strlen(s_path->u_name))) == NULL) {
2170         return AFPERR_MISC;
2171     }
2172
2173     if ( movecwd( vol, dir ) < 0 ) {
2174         return( AFPERR_PARAM );
2175     }
2176
2177     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2178     if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad ) < 0)  {
2179         if (vol_noadouble(vol))
2180             goto createdir_done;
2181         return( AFPERR_ACCESS );
2182     }
2183     ad_setname(&ad, s_path->m_name);
2184     ad_setid( &ad, s_path->st.st_dev, s_path->st.st_ino, dir->d_did, did, vol->v_stamp);
2185
2186     ad_flush( &ad);
2187     ad_close_metadata( &ad);
2188
2189 createdir_done:
2190     memcpy( rbuf, &dir->d_did, sizeof( u_int32_t ));
2191     *rbuflen = sizeof( u_int32_t );
2192     setvoltime(obj, vol );
2193     return( AFP_OK );
2194 }
2195
2196 /*
2197  * dst       new unix filename (not a pathname)
2198  * newname   new mac name
2199  * newparent curdir
2200  * dirfd     -1 means ignore dirfd (or use AT_FDCWD), otherwise src is relative to dirfd
2201  */
2202 int renamedir(const struct vol *vol,
2203               int dirfd,
2204               char *src,
2205               char *dst,
2206               struct dir *dir,
2207               struct dir *newparent,
2208               char *newname)
2209 {
2210     struct adouble  ad;
2211     int             err;
2212
2213     /* existence check moved to afp_moveandrename */
2214     if ( unix_rename(dirfd, src, -1, dst ) < 0 ) {
2215         switch ( errno ) {
2216         case ENOENT :
2217             return( AFPERR_NOOBJ );
2218         case EACCES :
2219             return( AFPERR_ACCESS );
2220         case EROFS:
2221             return AFPERR_VLOCK;
2222         case EINVAL:
2223             /* tried to move directory into a subdirectory of itself */
2224             return AFPERR_CANTMOVE;
2225         case EXDEV:
2226             /* this needs to copy and delete. bleah. that means we have
2227              * to deal with entire directory hierarchies. */
2228             if ((err = copydir(vol, dirfd, src, dst)) < 0) {
2229                 deletedir(-1, dst);
2230                 return err;
2231             }
2232             if ((err = deletedir(dirfd, src)) < 0)
2233                 return err;
2234             break;
2235         default :
2236             return( AFPERR_PARAM );
2237         }
2238     }
2239
2240     vol->vfs->vfs_renamedir(vol, dirfd, src, dst);
2241
2242     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2243
2244     if (!ad_open_metadata( dst, ADFLAGS_DIR, 0, &ad)) {
2245         ad_setname(&ad, newname);
2246         ad_flush( &ad);
2247         ad_close_metadata( &ad);
2248     }
2249
2250     return( AFP_OK );
2251 }
2252
2253 /* delete an empty directory */
2254 int deletecurdir(struct vol *vol)
2255 {
2256     struct dirent *de;
2257     struct stat st;
2258     struct dir  *fdir, *pdir;
2259     DIR *dp;
2260     struct adouble  ad;
2261     u_int16_t       ashort;
2262     int err;
2263
2264     if ((pdir = dirlookup(vol, curdir->d_pdid)) == NULL) {
2265         return( AFPERR_ACCESS );
2266     }
2267
2268     fdir = curdir;
2269
2270     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2271     /* we never want to create a resource fork here, we are going to delete it */
2272     if ( ad_metadata( ".", ADFLAGS_DIR, &ad) == 0 ) {
2273
2274         ad_getattr(&ad, &ashort);
2275         ad_close_metadata(&ad);
2276         if ((ashort & htons(ATTRBIT_NODELETE))) {
2277             return  AFPERR_OLOCK;
2278         }
2279     }
2280     err = vol->vfs->vfs_deletecurdir(vol);
2281     if (err) {
2282         LOG(log_error, logtype_afpd, "deletecurdir: error deleting .AppleDouble in \"%s\"",
2283             curdir->d_fullpath);
2284         return err;
2285     }
2286
2287     /* now get rid of dangling symlinks */
2288     if ((dp = opendir("."))) {
2289         while ((de = readdir(dp))) {
2290             /* skip this and previous directory */
2291             if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
2292                 continue;
2293
2294             /* bail if it's not a symlink */
2295             if ((lstat(de->d_name, &st) == 0) && !S_ISLNK(st.st_mode)) {
2296                 LOG(log_error, logtype_afpd, "deletecurdir(\"%s\"): not empty",
2297                     curdir->d_fullpath);
2298                 closedir(dp);
2299                 return AFPERR_DIRNEMPT;
2300             }
2301
2302             if ((err = netatalk_unlink(de->d_name))) {
2303                 closedir(dp);
2304                 return err;
2305             }
2306         }
2307     }
2308
2309     if (movecwd(vol, pdir) < 0) {
2310         err = afp_errno;
2311         goto delete_done;
2312     }
2313
2314     LOG(log_debug, logtype_afpd, "deletecurdir: moved to \"%s\"",
2315         cfrombstr(curdir->d_fullpath));
2316
2317     err = netatalk_rmdir_all_errors(-1, cfrombstr(fdir->d_u_name));
2318     if ( err ==  AFP_OK || err == AFPERR_NOOBJ) {
2319         cnid_delete(vol->v_cdb, fdir->d_did);
2320         dir_remove( vol, fdir );
2321     } else {
2322         LOG(log_error, logtype_afpd, "deletecurdir(\"%s\"): netatalk_rmdir_all_errors error",
2323             curdir->d_fullpath);
2324     }
2325
2326 delete_done:
2327     if (dp) {
2328         /* inode is used as key for cnid.
2329          * Close the descriptor only after cnid_delete
2330          * has been called.
2331          */
2332         closedir(dp);
2333     }
2334     return err;
2335 }
2336
2337 int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2338 {
2339     struct passwd   *pw;
2340     struct group    *gr;
2341     char        *name;
2342     u_int32_t           id;
2343     int         len, sfunc;
2344     int         utf8 = 0;
2345
2346     ibuf++;
2347     sfunc = (unsigned char) *ibuf++;
2348     *rbuflen = 0;
2349
2350     if (sfunc >= 3 && sfunc <= 6) {
2351         if (afp_version < 30) {
2352             return( AFPERR_PARAM );
2353         }
2354         utf8 = 1;
2355     }
2356
2357     switch ( sfunc ) {
2358     case 1 :
2359     case 3 :/* unicode */
2360         memcpy( &id, ibuf, sizeof( id ));
2361         id = ntohl(id);
2362         if ( id != 0 ) {
2363             if (( pw = getpwuid( id )) == NULL ) {
2364                 return( AFPERR_NOITEM );
2365             }
2366             len = convert_string_allocate( obj->options.unixcharset, ((!utf8)?obj->options.maccharset:CH_UTF8_MAC),
2367                                            pw->pw_name, -1, &name);
2368         } else {
2369             len = 0;
2370             name = NULL;
2371         }
2372         break;
2373     case 2 :
2374     case 4 : /* unicode */
2375         memcpy( &id, ibuf, sizeof( id ));
2376         id = ntohl(id);
2377         if ( id != 0 ) {
2378             if (NULL == ( gr = (struct group *)getgrgid( id ))) {
2379                 return( AFPERR_NOITEM );
2380             }
2381             len = convert_string_allocate( obj->options.unixcharset, (!utf8)?obj->options.maccharset:CH_UTF8_MAC,
2382                                            gr->gr_name, -1, &name);
2383         } else {
2384             len = 0;
2385             name = NULL;
2386         }
2387         break;
2388
2389     case 5 : /* UUID -> username */
2390     case 6 : /* UUID -> groupname */
2391         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2392             return AFPERR_PARAM;
2393         LOG(log_debug, logtype_afpd, "afp_mapid: valid UUID request");
2394         uuidtype_t type;
2395         len = getnamefromuuid((unsigned char*) ibuf, &name, &type);
2396         if (len != 0)       /* its a error code, not len */
2397             return AFPERR_NOITEM;
2398         switch (type) {
2399         case UUID_USER:
2400             if (( pw = getpwnam( name )) == NULL )
2401                 return( AFPERR_NOITEM );
2402             LOG(log_debug, logtype_afpd, "afp_mapid: name:%s -> uid:%d", name, pw->pw_uid);
2403             id = htonl(UUID_USER);
2404             memcpy( rbuf, &id, sizeof( id ));
2405             id = htonl( pw->pw_uid);
2406             rbuf += sizeof( id );
2407             memcpy( rbuf, &id, sizeof( id ));
2408             rbuf += sizeof( id );
2409             *rbuflen = 2 * sizeof( id );
2410             break;
2411         case UUID_GROUP:
2412             if (( gr = getgrnam( name )) == NULL )
2413                 return( AFPERR_NOITEM );
2414             LOG(log_debug, logtype_afpd, "afp_mapid: group:%s -> gid:%d", name, gr->gr_gid);
2415             id = htonl(UUID_GROUP);
2416             memcpy( rbuf, &id, sizeof( id ));
2417             rbuf += sizeof( id );
2418             id = htonl( gr->gr_gid);
2419             memcpy( rbuf, &id, sizeof( id ));
2420             rbuf += sizeof( id );
2421             *rbuflen = 2 * sizeof( id );
2422             break;
2423         case UUID_LOCAL:
2424             free(name);
2425             return (AFPERR_NOITEM);
2426         default:
2427             return AFPERR_MISC;
2428         }
2429         break;
2430
2431     default :
2432         return( AFPERR_PARAM );
2433     }
2434
2435     if (name)
2436         len = strlen( name );
2437
2438     if (utf8) {
2439         u_int16_t tp = htons(len);
2440         memcpy(rbuf, &tp, sizeof(tp));
2441         rbuf += sizeof(tp);
2442         *rbuflen += 2;
2443     }
2444     else {
2445         *rbuf++ = len;
2446         *rbuflen += 1;
2447     }
2448     if ( len > 0 ) {
2449         memcpy( rbuf, name, len );
2450     }
2451     *rbuflen += len;
2452     if (name)
2453         free(name);
2454     return( AFP_OK );
2455 }
2456
2457 int afp_mapname(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2458 {
2459     struct passwd   *pw;
2460     struct group    *gr;
2461     int             len, sfunc;
2462     u_int32_t       id;
2463     u_int16_t       ulen;
2464
2465     ibuf++;
2466     sfunc = (unsigned char) *ibuf++;
2467     *rbuflen = 0;
2468     LOG(log_debug, logtype_afpd, "afp_mapname: sfunc: %d, afp_version: %d", sfunc, afp_version);
2469     switch ( sfunc ) {
2470     case 1 :
2471     case 2 : /* unicode */
2472         if (afp_version < 30) {
2473             return( AFPERR_PARAM );
2474         }
2475         memcpy(&ulen, ibuf, sizeof(ulen));
2476         len = ntohs(ulen);
2477         ibuf += 2;
2478         LOG(log_debug, logtype_afpd, "afp_mapname: alive");
2479         break;
2480     case 3 :
2481     case 4 :
2482         len = (unsigned char) *ibuf++;
2483         break;
2484     case 5 : /* username -> UUID  */
2485     case 6 : /* groupname -> UUID */
2486         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2487             return AFPERR_PARAM;
2488         memcpy(&ulen, ibuf, sizeof(ulen));
2489         len = ntohs(ulen);
2490         ibuf += 2;
2491         break;
2492     default :
2493         return( AFPERR_PARAM );
2494     }
2495
2496     ibuf[ len ] = '\0';
2497
2498     if ( len == 0 )
2499         return AFPERR_PARAM;
2500     else {
2501         switch ( sfunc ) {
2502         case 1 : /* unicode */
2503         case 3 :
2504             if (NULL == ( pw = (struct passwd *)getpwnam( ibuf )) ) {
2505                 return( AFPERR_NOITEM );
2506             }
2507             id = pw->pw_uid;
2508             id = htonl(id);
2509             memcpy( rbuf, &id, sizeof( id ));
2510             *rbuflen = sizeof( id );
2511             break;
2512
2513         case 2 : /* unicode */
2514         case 4 :
2515             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s",ibuf);
2516             if (NULL == ( gr = (struct group *)getgrnam( ibuf ))) {
2517                 return( AFPERR_NOITEM );
2518             }
2519             id = gr->gr_gid;
2520             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s -> id: %d",ibuf, id);
2521             id = htonl(id);
2522             memcpy( rbuf, &id, sizeof( id ));
2523             *rbuflen = sizeof( id );
2524             break;
2525         case 5 :        /* username -> UUID */
2526             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2527             if (0 != getuuidfromname(ibuf, UUID_USER, (unsigned char *)rbuf))
2528                 return AFPERR_NOITEM;
2529             *rbuflen = UUID_BINSIZE;
2530             break;
2531         case 6 :        /* groupname -> UUID */
2532             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2533             if (0 != getuuidfromname(ibuf, UUID_GROUP, (unsigned char *)rbuf))
2534                 return AFPERR_NOITEM;
2535             *rbuflen = UUID_BINSIZE;
2536             break;
2537         }
2538     }
2539     return( AFP_OK );
2540 }
2541
2542 /* ------------------------------------
2543    variable DID support
2544 */
2545 int afp_closedir(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2546 {
2547 #if 0
2548     struct vol   *vol;
2549     struct dir   *dir;
2550     u_int16_t    vid;
2551     u_int32_t    did;
2552 #endif /* 0 */
2553
2554     *rbuflen = 0;
2555
2556     /* do nothing as dids are static for the life of the process. */
2557 #if 0
2558     ibuf += 2;
2559
2560     memcpy(&vid,  ibuf, sizeof( vid ));
2561     ibuf += sizeof( vid );
2562     if (( vol = getvolbyvid( vid )) == NULL ) {
2563         return( AFPERR_PARAM );
2564     }
2565
2566     memcpy( &did, ibuf, sizeof( did ));
2567     ibuf += sizeof( did );
2568     if (( dir = dirlookup( vol, did )) == NULL ) {
2569         return( AFPERR_PARAM );
2570     }
2571
2572     /* dir_remove -- deletedid */
2573 #endif /* 0 */
2574
2575     return AFP_OK;
2576 }
2577
2578 /* did creation gets done automatically
2579  * there's a pb again with case but move it to cname
2580  */
2581 int afp_opendir(AFPObj *obj _U_, char *ibuf, size_t ibuflen  _U_, char *rbuf, size_t *rbuflen)
2582 {
2583     struct vol      *vol;
2584     struct dir      *parentdir;
2585     struct path     *path;
2586     u_int32_t       did;
2587     u_int16_t       vid;
2588
2589     *rbuflen = 0;
2590     ibuf += 2;
2591
2592     memcpy(&vid, ibuf, sizeof(vid));
2593     ibuf += sizeof( vid );
2594
2595     if (NULL == ( vol = getvolbyvid( vid )) ) {
2596         return( AFPERR_PARAM );
2597     }
2598
2599     memcpy(&did, ibuf, sizeof(did));
2600     ibuf += sizeof(did);
2601
2602     if (NULL == ( parentdir = dirlookup( vol, did )) ) {
2603         return afp_errno;
2604     }
2605
2606     if (NULL == ( path = cname( vol, parentdir, &ibuf )) ) {
2607         return get_afp_errno(AFPERR_PARAM);
2608     }
2609
2610     if ( *path->m_name != '\0' ) {
2611         return path_error(path, AFPERR_NOOBJ);
2612     }
2613
2614     if ( !path->st_valid && of_stat(path ) < 0 ) {
2615         return( AFPERR_NOOBJ );
2616     }
2617     if ( path->st_errno ) {
2618         return( AFPERR_NOOBJ );
2619     }
2620
2621     memcpy(rbuf, &curdir->d_did, sizeof(curdir->d_did));
2622     *rbuflen = sizeof(curdir->d_did);
2623     return AFP_OK;
2624 }