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