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