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