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