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