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