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