]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/directory.c
dircache: support locking of dirs which prevent cache removal.
[netatalk.git] / etc / afpd / directory.c
1 /*
2  * $Id: directory.c,v 1.131.2.10 2010-02-05 10:27:58 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
873   FIXME: open forks ??!!!
874
875  * @brief Remove a dir from a cache and free it and any ressources with it
876  *
877  * @param (r) pointer to struct vol
878  * @param (rw) pointer to struct dir
879  */
880 int dir_remove(const struct vol *vol, struct dir *dir)
881 {
882     assert(vol);
883     assert(dir);
884
885     if (dir->d_did == DIRDID_ROOT_PARENT || dir->d_did == DIRDID_ROOT)
886         return 0;
887
888     if (dir->d_flags & DIRF_CACHELOCK) {
889         LOG(log_warning, logtype_afpd, "dir_remove(did:%u,'%s'): attempt to remove a locked dir",
890             ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
891         return 0;
892     }
893
894     if (curdir == dir) {
895         if (movecwd(vol, vol->v_root) < 0) {
896             LOG(log_error, logtype_afpd, "dir_remove: can't chdir to : %s", vol->v_root);
897         }
898     }
899
900     LOG(log_debug, logtype_afpd, "dir_remove(did:%u,'%s'): {removing}",
901         ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
902
903     dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX);
904     dir_free(dir);
905
906     return 0;
907 }
908
909 /*!
910  * @brief Modify a struct dir, adjust cache
911  *
912  * Any value that is 0 or NULL is not changed. If new_uname is NULL it is set to new_mname.
913  * If given new_uname == new_mname, new_uname will point to new_mname.
914  *
915  * @param vol       (r) pointer to struct vol
916  * @param dir       (rw) pointer to struct dir
917  * @param pdid      (r) new parent DID
918  * @param did       (r) new DID
919  * @param new_mname (r) new mac-name
920  * @param new_uname (r) new unix-name
921  */
922 int dir_modify(const struct vol *vol,
923                struct dir *dir,
924                cnid_t pdid,
925                cnid_t did,
926                const char *new_mname,
927                const char *new_uname,
928                bstring pdir_fullpath)
929 {
930     int ret = 0;
931
932     /* Remove it from the cache */
933     dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX);
934
935     if (pdid)
936         dir->d_pdid = pdid;
937     if (did)
938         dir->d_did = did;
939
940     if (new_mname) {
941         /* free uname if it's not the same as mname */
942         if (dir->d_m_name != dir->d_u_name)
943             bdestroy(dir->d_u_name);
944
945         if (new_uname == NULL)
946             new_uname = new_mname;
947
948         /* assign new name */
949         if ((bassigncstr(dir->d_m_name, new_mname)) != BSTR_OK) {
950             LOG(log_error, logtype_afpd, "dir_modify: bassigncstr: %s", strerror(errno) );
951             return -1;
952         }
953
954         if (new_mname == new_uname || (strcmp(new_mname, new_uname) == 0)) {
955             dir->d_u_name = dir->d_m_name;
956         } else {
957             if ((dir->d_u_name = bfromcstr(new_uname)) == NULL) {
958                 LOG(log_error, logtype_afpd, "renamedir: bassigncstr: %s", strerror(errno) );
959                 return -1;
960             }
961         }
962     }
963
964     if (pdir_fullpath) {
965         if (bassign(dir->d_fullpath, pdir_fullpath) != BSTR_OK)
966             return -1;
967         if (bcatcstr(dir->d_fullpath, "/") != BSTR_OK)
968             return -1;
969         if (bcatcstr(dir->d_fullpath, new_uname) != BSTR_OK)
970             return -1;
971     }
972
973     if (dir->d_m_name_ucs2)
974         free(dir->d_m_name_ucs2);
975     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))
976         dir->d_m_name_ucs2 = NULL;
977
978     /* Re-add it to the cache */
979     if ((dircache_add(dir)) != 0) {
980         dircache_dump();
981         exit(EXITERR_SYS);
982     }
983
984     return ret;
985 }
986
987 /*!
988  * @brief Resolve a catalog node name path
989  *
990  * If it's a filename:
991  * 1. compute unix name
992  * 2. stat the file, storing struct stat or errno in struct path
993  * 3. cwd (and curdir) is filename parent directory
994  * 4. return path with with filename
995  *
996  * If it's a dirname:
997  * 5. search the dircache
998  * 6. if not in the cache:
999  * 7.     compute unix name
1000  * 8.     stat the dir, storing struct stat or errno in struct path
1001  * 9.     chdir dirname
1002  * 10.    if chdir failed, return path with dirname
1003  *                         cwd is dir parent directory
1004  *        if chdir succeeded, add to dircache
1005  *                            return path with "" and "."
1006  *                            cwd is dirname
1007  * 11. else in the cache:
1008  * 12.     stat the dir, storing struct stat or errno in struct path
1009  * 13.     chdir dirname
1010  * 14.     if chdir failed
1011  *             if ENOENT
1012  *                 remove from cache
1013  *             if not last path part, return NULL
1014  *             else 
1015    return
1016    if chdir error
1017    dirname
1018    curdir: dir parent directory
1019    else
1020    dirname: ""
1021    curdir: dir
1022 */
1023 struct path *cname(struct vol *vol, struct dir *dir, char **cpath)
1024 {
1025     static char        path[ MAXPATHLEN + 1];
1026     static struct path ret;
1027
1028     struct dir  *cdir;
1029     char        *data, *p;
1030     int         len;
1031     u_int32_t   hint;
1032     u_int16_t   len16;
1033     int         size = 0;
1034     int         toUTF8 = 0;
1035
1036     LOG(log_maxdebug, logtype_afpd, "came('%s'): {start}", cfrombstring(dir->d_fullpath));
1037
1038     data = *cpath;
1039     afp_errno = AFPERR_NOOBJ;
1040     memset(&ret, 0, sizeof(ret));
1041
1042     switch (ret.m_type = *data) { /* path type */
1043     case 2:
1044         data++;
1045         len = (unsigned char) *data++;
1046         size = 2;
1047         if (afp_version >= 30) {
1048             ret.m_type = 3;
1049             toUTF8 = 1;
1050         }
1051         break;
1052     case 3:
1053         if (afp_version >= 30) {
1054             data++;
1055             memcpy(&hint, data, sizeof(hint));
1056             hint = ntohl(hint);
1057             data += sizeof(hint);
1058
1059             memcpy(&len16, data, sizeof(len16));
1060             len = ntohs(len16);
1061             data += 2;
1062             size = 7;
1063             break;
1064         }
1065         /* else it's an error */
1066     default:
1067         afp_errno = AFPERR_PARAM;
1068         return( NULL );
1069     }
1070     *cpath += len + size;
1071
1072     path[0] = 0;
1073     ret.m_name = path;
1074
1075     if (movecwd(vol, dir) < 0 ) {
1076         LOG(log_debug, logtype_afpd, "cname(did:%u): failed to chdir to '%s'",
1077             ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
1078         if (len == 0)
1079             return path_from_dir(vol, dir, &ret);
1080         else
1081             return NULL;
1082     }
1083
1084     while (len) {
1085         /*
1086          * Three cases:
1087          * 1. single 0 -> delimiter
1088          * 2. additional 0 -> chdir(..)
1089          * 3. a name
1090          *    a) name is a file, build struct path from it etc., exit while loop
1091          *    b) name is a dir, add it to the dircache, chdir to it, continue
1092          */
1093         if (*data == 0) { /* case 1 or 2 */
1094             data++;
1095             len--;
1096             while (len > 0 && *data == 0) { /* case 2 */
1097                 /* chdir to parrent dir */
1098                 if ((dir = dirlookup(vol, dir->d_pdid)) == NULL)
1099                     return NULL;
1100                 if (movecwd( vol, dir ) < 0 ) {
1101                     dir_remove(vol, dir);
1102                     return NULL;
1103                 }
1104                 data++;
1105                 len--;
1106             }
1107             continue;
1108         }
1109
1110         /* case 3: copy name from packet buffer to ret.m_name and process it */
1111         for ( p = path; *data != 0 && len > 0; len-- ) {
1112             *p++ = *data++;
1113             if (p > &path[ MAXPATHLEN]) {
1114                 afp_errno = AFPERR_PARAM;
1115                 return NULL;
1116             }
1117         }
1118         *p = 0;            /* Terminate string */
1119         ret.u_name = NULL;
1120
1121         /* Get u_name from m_name */
1122         if (cname_mtouname(vol, dir, &ret, toUTF8) != 0) {
1123             LOG(log_error, logtype_afpd, "cname('%s'): error from cname_mtouname", path);
1124             return NULL;
1125         }
1126
1127         LOG(log_maxdebug, logtype_afpd, "came('%s'): {node: '%s}", cfrombstring(dir->d_fullpath), ret.u_name);
1128
1129         /* Prevent access to our special folders like .AppleDouble */
1130         if (check_name(vol, ret.u_name)) {
1131             /* the name is illegal */
1132             LOG(log_info, logtype_afpd, "cname: illegal path: '%s'", ret.u_name);
1133             afp_errno = AFPERR_PARAM;
1134             return NULL;
1135         }
1136
1137         if (dir->d_did == DIRDID_ROOT_PARENT) {
1138             /*
1139              * Special case: CNID 1
1140              * root parent (did 1) has one child: the volume. Requests for did=1 with
1141              * some <name> must check against the volume name.
1142              */
1143             if ((strcmp(cfrombstring(vol->v_root->d_m_name), ret.m_name)) == 0)
1144                 cdir = vol->v_root;
1145             else
1146                 return NULL;
1147         } else {
1148             /*
1149              * CNID != 1, eg. most of the times we take this way.
1150              * Now check if current path-part is a file or dir:
1151              * o if it's dir we have to step into it
1152              * o if it's a file we expect it to be the last part of the requested path
1153              *   and thus call continue which should terminate the while loop because
1154              *   len = 0. Ok?
1155              */
1156             if (of_stat(&ret) != 0) {
1157                 /*
1158                  * ret.u_name doesn't exist, might be afp_createfile|dir
1159                  * that means it should have been the last part
1160                  */
1161                 if (len > 0) {
1162                     /* it wasn't the last part, so we have a bogus path request */
1163                     afp_errno = AFPERR_NOOBJ;
1164                     return NULL;
1165                 }
1166                 /*
1167                  * this will terminate clean in while (1) because len == 0,
1168                  * probably afp_createfile|dir
1169                  */
1170                 LOG(log_maxdebug, logtype_afpd, "came('%s'): {leave-cnode ENOENT (possile create request): '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
1171                 continue;
1172             }
1173
1174             switch (ret.st.st_mode & S_IFMT) {
1175             case S_IFREG:
1176                 LOG(log_debug, logtype_afpd, "came('%s'): {file: '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
1177                 if (len > 0) {
1178                     /* it wasn't the last part, so we have a bogus path request */
1179                     afp_errno = AFPERR_PARAM;
1180                     return NULL;
1181                 }
1182                 continue; /* continues while loop */
1183             case S_IFLNK:
1184                 LOG(log_debug, logtype_afpd, "came('%s'): {link: '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
1185                 if (len > 0) {
1186                     LOG(log_warning, logtype_afpd, "came('%s'): {symlinked dir: '%s'}", cfrombstring(dir->d_fullpath), ret.u_name);
1187                     afp_errno = AFPERR_PARAM;
1188                     return NULL;
1189                 }
1190                 continue; /* continues while loop */
1191             case S_IFDIR:
1192                 break;
1193             default:
1194                 LOG(log_info, logtype_afpd, "cname: special file: '%s'", ret.u_name);
1195                 afp_errno = AFPERR_NODIR;
1196                 return NULL;
1197             }
1198
1199             /* Search the cache */
1200             int unamelen = strlen(ret.u_name);
1201             cdir = dircache_search_by_name(vol, dir, ret.u_name, unamelen);
1202             if (cdir == NULL) {
1203                 /* Not in cache, create one */
1204                 if ((cdir = dir_add(vol, dir, &ret, unamelen)) == NULL) {
1205                     LOG(log_error, logtype_afpd, "cname(did:%u, name:'%s', cwd:'%s'): failed to add dir",
1206                         ntohl(dir->d_did), ret.u_name, getcwdpath());
1207                     return NULL;
1208                 }
1209             }
1210         } /* if/else cnid==1 */
1211
1212         /* Now chdir to the evaluated dir */
1213         if (movecwd( vol, cdir ) < 0 ) {
1214             LOG(log_debug, logtype_afpd, "cname(cwd:'%s'): failed to chdir to new subdir '%s': %s",
1215                 cfrombstring(curdir->d_fullpath), cfrombstring(cdir->d_fullpath), strerror(errno));
1216             if (len == 0)
1217                 return path_from_dir(vol, cdir, &ret);
1218             else
1219                 return NULL;
1220         }
1221         dir = cdir;
1222         ret.m_name[0] = 0;      /* so we later know last token was a dir */
1223     } /* while (len) */
1224
1225     if (curdir->d_did == DIRDID_ROOT_PARENT) {
1226         afp_errno = AFPERR_DID1;
1227         return NULL;
1228     }
1229
1230     if (ret.m_name[0] == 0) {
1231         /* Last part was a dir */
1232         ret.u_name = mtoupath(vol, ret.m_name, 0, 1); /* Force "." into a useable static buffer */
1233         ret.d_dir = dir;
1234     }
1235
1236     LOG(log_debug, logtype_afpd, "came('%s') {end: curdir:'%s', path:'%s'}",
1237         cfrombstring(dir->d_fullpath),
1238         cfrombstring(curdir->d_fullpath),
1239         ret.u_name);
1240
1241     return &ret;
1242 }
1243
1244 /*
1245  * @brief chdir() to dir
1246  *
1247  * @param vol   (r) pointer to struct vol
1248  * @param dir   (r) pointer to struct dir
1249  *
1250  * @returns 0 on success, -1 on error with afp_errno set appropiately
1251  */
1252 int movecwd(const struct vol *vol, struct dir *dir)
1253 {
1254     assert(vol);
1255
1256     if (dir == NULL)
1257         return -1;
1258
1259     LOG(log_maxdebug, logtype_afpd, "movecwd(curdir:'%s', cwd:'%s')", 
1260         cfrombstring(curdir->d_fullpath), getcwdpath());
1261
1262     if ( dir == curdir)
1263         return( 0 );
1264     if (dir->d_did == DIRDID_ROOT_PARENT) {
1265         curdir = &rootParent;
1266         return 0;
1267     }
1268
1269     LOG(log_debug, logtype_afpd, "movecwd(did:%u, '%s')", ntohl(dir->d_did), cfrombstring(dir->d_fullpath));
1270
1271     if ( chdir(cfrombstring(dir->d_fullpath)) < 0 ) {
1272         LOG(log_debug, logtype_afpd, "movecwd('%s'): %s", cfrombstring(dir->d_fullpath), strerror(errno));
1273         switch (errno) {
1274         case EACCES:
1275         case EPERM:
1276             afp_errno = AFPERR_ACCESS;
1277             break;
1278         default:
1279             afp_errno = AFPERR_NOOBJ;
1280         }
1281         return( -1 );
1282     }
1283
1284     curdir = dir;
1285     return( 0 );
1286 }
1287
1288 /*
1289  * We can't use unix file's perm to support Apple's inherited protection modes.
1290  * If we aren't the file's owner we can't change its perms when moving it and smb
1291  * nfs,... don't even try.
1292  */
1293 #define AFP_CHECK_ACCESS
1294
1295 int check_access(char *path, int mode)
1296 {
1297 #ifdef AFP_CHECK_ACCESS
1298     struct maccess ma;
1299     char *p;
1300
1301     p = ad_dir(path);
1302     if (!p)
1303         return -1;
1304
1305     accessmode(p, &ma, curdir, NULL);
1306     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE))
1307         return -1;
1308     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD))
1309         return -1;
1310 #endif
1311     return 0;
1312 }
1313
1314 /* --------------------- */
1315 int file_access(struct path *path, int mode)
1316 {
1317     struct maccess ma;
1318
1319     accessmode(path->u_name, &ma, curdir, &path->st);
1320     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE))
1321         return -1;
1322     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD))
1323         return -1;
1324     return 0;
1325
1326 }
1327
1328 /* --------------------- */
1329 void setdiroffcnt(struct dir *dir, struct stat *st,  u_int32_t count)
1330 {
1331     dir->offcnt = count;
1332     dir->ctime = st->st_ctime;
1333     dir->d_flags &= ~DIRF_CNID;
1334 }
1335
1336
1337 /* ---------------------
1338  * is our cached also for reenumerate id?
1339  */
1340 int dirreenumerate(struct dir *dir, struct stat *st)
1341 {
1342     return st->st_ctime == dir->ctime && (dir->d_flags & DIRF_CNID);
1343 }
1344
1345 /* ------------------------------
1346    (".", curdir)
1347    (name, dir) with curdir:name == dir, from afp_enumerate
1348 */
1349
1350 int getdirparams(const struct vol *vol,
1351                  u_int16_t bitmap, struct path *s_path,
1352                  struct dir *dir,
1353                  char *buf, size_t *buflen )
1354 {
1355     struct maccess  ma;
1356     struct adouble  ad;
1357     char        *data, *l_nameoff = NULL, *utf_nameoff = NULL;
1358     int         bit = 0, isad = 0;
1359     u_int32_t           aint;
1360     u_int16_t       ashort;
1361     int                 ret;
1362     u_int32_t           utf8 = 0;
1363     cnid_t              pdid;
1364     struct stat *st = &s_path->st;
1365     char *upath = s_path->u_name;
1366
1367     if ((bitmap & ((1 << DIRPBIT_ATTR)  |
1368                    (1 << DIRPBIT_CDATE) |
1369                    (1 << DIRPBIT_MDATE) |
1370                    (1 << DIRPBIT_BDATE) |
1371                    (1 << DIRPBIT_FINFO)))) {
1372
1373         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1374         if ( !ad_metadata( upath, ADFLAGS_CREATE|ADFLAGS_DIR, &ad) ) {
1375             isad = 1;
1376             if (ad.ad_md->adf_flags & O_CREAT) {
1377                 /* We just created it */
1378                 ad_setname(&ad, s_path->m_name);
1379                 ad_setid( &ad,
1380                           s_path->st.st_dev,
1381                           s_path->st.st_ino,
1382                           dir->d_did,
1383                           dir->d_pdid,
1384                           vol->v_stamp);
1385                 ad_flush( &ad);
1386             }
1387         }
1388     }
1389
1390     pdid = dir->d_pdid;
1391
1392     data = buf;
1393     while ( bitmap != 0 ) {
1394         while (( bitmap & 1 ) == 0 ) {
1395             bitmap = bitmap>>1;
1396             bit++;
1397         }
1398
1399         switch ( bit ) {
1400         case DIRPBIT_ATTR :
1401             if ( isad ) {
1402                 ad_getattr(&ad, &ashort);
1403             } else if (invisible_dots(vol, cfrombstring(dir->d_u_name))) {
1404                 ashort = htons(ATTRBIT_INVISIBLE);
1405             } else
1406                 ashort = 0;
1407             ashort |= htons(ATTRBIT_SHARED);
1408             memcpy( data, &ashort, sizeof( ashort ));
1409             data += sizeof( ashort );
1410             break;
1411
1412         case DIRPBIT_PDID :
1413             memcpy( data, &pdid, sizeof( pdid ));
1414             data += sizeof( pdid );
1415             LOG(log_debug, logtype_afpd, "metadata('%s'):     Parent DID: %u",
1416                 s_path->u_name, ntohl(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             LOG(log_debug, logtype_afpd, "metadata('%s'):            DID: %u",
1474                 s_path->u_name, ntohl(dir->d_did));
1475             break;
1476
1477         case DIRPBIT_OFFCNT :
1478             ashort = 0;
1479             /* this needs to handle current directory access rights */
1480             if (diroffcnt(dir, st)) {
1481                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1482             }
1483             else if ((ret = for_each_dirent(vol, upath, NULL,NULL)) >= 0) {
1484                 setdiroffcnt(dir, st,  ret);
1485                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1486             }
1487             ashort = htons( ashort );
1488             memcpy( data, &ashort, sizeof( ashort ));
1489             data += sizeof( ashort );
1490             break;
1491
1492         case DIRPBIT_UID :
1493             aint = htonl(st->st_uid);
1494             memcpy( data, &aint, sizeof( aint ));
1495             data += sizeof( aint );
1496             break;
1497
1498         case DIRPBIT_GID :
1499             aint = htonl(st->st_gid);
1500             memcpy( data, &aint, sizeof( aint ));
1501             data += sizeof( aint );
1502             break;
1503
1504         case DIRPBIT_ACCESS :
1505             accessmode( upath, &ma, dir , st);
1506
1507             *data++ = ma.ma_user;
1508             *data++ = ma.ma_world;
1509             *data++ = ma.ma_group;
1510             *data++ = ma.ma_owner;
1511             break;
1512
1513             /* Client has requested the ProDOS information block.
1514                Just pass back the same basic block for all
1515                directories. <shirsch@ibm.net> */
1516         case DIRPBIT_PDINFO :
1517             if (afp_version >= 30) { /* UTF8 name */
1518                 utf8 = kTextEncodingUTF8;
1519                 if (dir->d_m_name) /* root of parent can have a null name */
1520                     utf_nameoff = data;
1521                 else
1522                     memset(data, 0, sizeof(u_int16_t));
1523                 data += sizeof( u_int16_t );
1524                 aint = 0;
1525                 memcpy(data, &aint, sizeof( aint ));
1526                 data += sizeof( aint );
1527             }
1528             else { /* ProDOS Info Block */
1529                 *data++ = 0x0f;
1530                 *data++ = 0;
1531                 ashort = htons( 0x0200 );
1532                 memcpy( data, &ashort, sizeof( ashort ));
1533                 data += sizeof( ashort );
1534                 memset( data, 0, sizeof( ashort ));
1535                 data += sizeof( ashort );
1536             }
1537             break;
1538
1539         case DIRPBIT_UNIXPR :
1540             aint = htonl(st->st_uid);
1541             memcpy( data, &aint, sizeof( aint ));
1542             data += sizeof( aint );
1543             aint = htonl(st->st_gid);
1544             memcpy( data, &aint, sizeof( aint ));
1545             data += sizeof( aint );
1546
1547             aint = st->st_mode;
1548             aint = htonl ( aint & ~S_ISGID );  /* Remove SGID, OSX doesn't like it ... */
1549             memcpy( data, &aint, sizeof( aint ));
1550             data += sizeof( aint );
1551
1552             accessmode( upath, &ma, dir , st);
1553
1554             *data++ = ma.ma_user;
1555             *data++ = ma.ma_world;
1556             *data++ = ma.ma_group;
1557             *data++ = ma.ma_owner;
1558             break;
1559
1560         default :
1561             if ( isad ) {
1562                 ad_close_metadata( &ad );
1563             }
1564             return( AFPERR_BITMAP );
1565         }
1566         bitmap = bitmap>>1;
1567         bit++;
1568     }
1569     if ( l_nameoff ) {
1570         ashort = htons( data - buf );
1571         memcpy( l_nameoff, &ashort, sizeof( ashort ));
1572         data = set_name(vol, data, pdid, cfrombstring(dir->d_m_name), dir->d_did, 0);
1573     }
1574     if ( utf_nameoff ) {
1575         ashort = htons( data - buf );
1576         memcpy( utf_nameoff, &ashort, sizeof( ashort ));
1577         data = set_name(vol, data, pdid, cfrombstring(dir->d_m_name), dir->d_did, utf8);
1578     }
1579     if ( isad ) {
1580         ad_close_metadata( &ad );
1581     }
1582     *buflen = data - buf;
1583     return( AFP_OK );
1584 }
1585
1586 /* ----------------------------- */
1587 int path_error(struct path *path, int error)
1588 {
1589 /* - a dir with access error
1590  * - no error it's a file
1591  * - file not found
1592  */
1593     if (path_isadir(path))
1594         return afp_errno;
1595     if (path->st_valid && path->st_errno)
1596         return error;
1597     return AFPERR_BADTYPE ;
1598 }
1599
1600 /* ----------------------------- */
1601 int afp_setdirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
1602 {
1603     struct vol  *vol;
1604     struct dir  *dir;
1605     struct path *path;
1606     u_int16_t   vid, bitmap;
1607     u_int32_t   did;
1608     int     rc;
1609
1610     *rbuflen = 0;
1611     ibuf += 2;
1612     memcpy( &vid, ibuf, sizeof( vid ));
1613     ibuf += sizeof( vid );
1614
1615     if (NULL == ( vol = getvolbyvid( vid )) ) {
1616         return( AFPERR_PARAM );
1617     }
1618
1619     if (vol->v_flags & AFPVOL_RO)
1620         return AFPERR_VLOCK;
1621
1622     memcpy( &did, ibuf, sizeof( did ));
1623     ibuf += sizeof( int );
1624
1625     if (NULL == ( dir = dirlookup( vol, did )) ) {
1626         return afp_errno;
1627     }
1628
1629     memcpy( &bitmap, ibuf, sizeof( bitmap ));
1630     bitmap = ntohs( bitmap );
1631     ibuf += sizeof( bitmap );
1632
1633     if (NULL == ( path = cname( vol, dir, &ibuf )) ) {
1634         return get_afp_errno(AFPERR_NOOBJ);
1635     }
1636
1637     if ( *path->m_name != '\0' ) {
1638         rc = path_error(path, AFPERR_NOOBJ);
1639         /* maybe we are trying to set perms back */
1640         if (rc != AFPERR_ACCESS)
1641             return rc;
1642     }
1643
1644     /*
1645      * If ibuf is odd, make it even.
1646      */
1647     if ((u_long)ibuf & 1 ) {
1648         ibuf++;
1649     }
1650
1651     if (AFP_OK == ( rc = setdirparams(vol, path, bitmap, ibuf )) ) {
1652         setvoltime(obj, vol );
1653     }
1654     return( rc );
1655 }
1656
1657 /*
1658  * cf AFP3.0.pdf page 244 for change_mdate and change_parent_mdate logic
1659  *
1660  * assume path == '\0' eg. it's a directory in canonical form
1661  */
1662 int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *buf )
1663 {
1664     struct maccess  ma;
1665     struct adouble  ad;
1666     struct utimbuf      ut;
1667     struct timeval      tv;
1668
1669     char                *upath;
1670     struct dir          *dir;
1671     int         bit, isad = 1;
1672     int                 cdate, bdate;
1673     int                 owner, group;
1674     u_int16_t       ashort, bshort, oshort;
1675     int                 err = AFP_OK;
1676     int                 change_mdate = 0;
1677     int                 change_parent_mdate = 0;
1678     int                 newdate = 0;
1679     u_int16_t           bitmap = d_bitmap;
1680     u_char              finder_buf[32];
1681     u_int32_t       upriv;
1682     mode_t              mpriv = 0;
1683     u_int16_t           upriv_bit = 0;
1684
1685     bit = 0;
1686     upath = path->u_name;
1687     dir   = path->d_dir;
1688     while ( bitmap != 0 ) {
1689         while (( bitmap & 1 ) == 0 ) {
1690             bitmap = bitmap>>1;
1691             bit++;
1692         }
1693
1694         switch( bit ) {
1695         case DIRPBIT_ATTR :
1696             change_mdate = 1;
1697             memcpy( &ashort, buf, sizeof( ashort ));
1698             buf += sizeof( ashort );
1699             break;
1700         case DIRPBIT_CDATE :
1701             change_mdate = 1;
1702             memcpy(&cdate, buf, sizeof(cdate));
1703             buf += sizeof( cdate );
1704             break;
1705         case DIRPBIT_MDATE :
1706             memcpy(&newdate, buf, sizeof(newdate));
1707             buf += sizeof( newdate );
1708             break;
1709         case DIRPBIT_BDATE :
1710             change_mdate = 1;
1711             memcpy(&bdate, buf, sizeof(bdate));
1712             buf += sizeof( bdate );
1713             break;
1714         case DIRPBIT_FINFO :
1715             change_mdate = 1;
1716             memcpy( finder_buf, buf, 32 );
1717             buf += 32;
1718             break;
1719         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1720             change_parent_mdate = 1;
1721             memcpy( &owner, buf, sizeof(owner));
1722             buf += sizeof( owner );
1723             break;
1724         case DIRPBIT_GID :
1725             change_parent_mdate = 1;
1726             memcpy( &group, buf, sizeof( group ));
1727             buf += sizeof( group );
1728             break;
1729         case DIRPBIT_ACCESS :
1730             change_mdate = 1;
1731             change_parent_mdate = 1;
1732             ma.ma_user = *buf++;
1733             ma.ma_world = *buf++;
1734             ma.ma_group = *buf++;
1735             ma.ma_owner = *buf++;
1736             mpriv = mtoumode( &ma ) | vol->v_dperm;
1737             if (dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1738                 err = set_dir_errors(path, "setdirmode", errno);
1739                 bitmap = 0;
1740             }
1741             break;
1742             /* Ignore what the client thinks we should do to the
1743                ProDOS information block.  Skip over the data and
1744                report nothing amiss. <shirsch@ibm.net> */
1745         case DIRPBIT_PDINFO :
1746             if (afp_version < 30) {
1747                 buf += 6;
1748             }
1749             else {
1750                 err = AFPERR_BITMAP;
1751                 bitmap = 0;
1752             }
1753             break;
1754         case DIRPBIT_UNIXPR :
1755             if (vol_unix_priv(vol)) {
1756                 memcpy( &owner, buf, sizeof(owner)); /* FIXME need to change owner too? */
1757                 buf += sizeof( owner );
1758                 memcpy( &group, buf, sizeof( group ));
1759                 buf += sizeof( group );
1760
1761                 change_mdate = 1;
1762                 change_parent_mdate = 1;
1763                 memcpy( &upriv, buf, sizeof( upriv ));
1764                 buf += sizeof( upriv );
1765                 upriv = ntohl (upriv) | vol->v_dperm;
1766                 if (dir_rx_set(upriv)) {
1767                     /* maybe we are trying to set perms back */
1768                     if ( setdirunixmode(vol, upath, upriv) < 0 ) {
1769                         bitmap = 0;
1770                         err = set_dir_errors(path, "setdirunixmode", errno);
1771                     }
1772                 }
1773                 else {
1774                     /* do it later */
1775                     upriv_bit = 1;
1776                 }
1777                 break;
1778             }
1779             /* fall through */
1780         default :
1781             err = AFPERR_BITMAP;
1782             bitmap = 0;
1783             break;
1784         }
1785
1786         bitmap = bitmap>>1;
1787         bit++;
1788     }
1789     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1790
1791     if (ad_open_metadata( upath, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
1792         /*
1793          * Check to see what we're trying to set.  If it's anything
1794          * but ACCESS, UID, or GID, give an error.  If it's any of those
1795          * three, we don't need the ad to be open, so just continue.
1796          *
1797          * note: we also don't need to worry about mdate. also, be quiet
1798          *       if we're using the noadouble option.
1799          */
1800         if (!vol_noadouble(vol) && (d_bitmap &
1801                                     ~((1<<DIRPBIT_ACCESS)|(1<<DIRPBIT_UNIXPR)|
1802                                       (1<<DIRPBIT_UID)|(1<<DIRPBIT_GID)|
1803                                       (1<<DIRPBIT_MDATE)|(1<<DIRPBIT_PDINFO)))) {
1804             return AFPERR_ACCESS;
1805         }
1806
1807         isad = 0;
1808     } else {
1809         /*
1810          * Check to see if a create was necessary. If it was, we'll want
1811          * to set our name, etc.
1812          */
1813         if ( (ad_get_HF_flags( &ad ) & O_CREAT)) {
1814             ad_setname(&ad, cfrombstring(curdir->d_m_name));
1815         }
1816     }
1817
1818     bit = 0;
1819     bitmap = d_bitmap;
1820     while ( bitmap != 0 ) {
1821         while (( bitmap & 1 ) == 0 ) {
1822             bitmap = bitmap>>1;
1823             bit++;
1824         }
1825
1826         switch( bit ) {
1827         case DIRPBIT_ATTR :
1828             if (isad) {
1829                 ad_getattr(&ad, &bshort);
1830                 oshort = bshort;
1831                 if ( ntohs( ashort ) & ATTRBIT_SETCLR ) {
1832                     bshort |= htons( ntohs( ashort ) & ~ATTRBIT_SETCLR );
1833                 } else {
1834                     bshort &= ~ashort;
1835                 }
1836                 if ((bshort & htons(ATTRBIT_INVISIBLE)) != (oshort & htons(ATTRBIT_INVISIBLE)))
1837                     change_parent_mdate = 1;
1838                 ad_setattr(&ad, bshort);
1839             }
1840             break;
1841         case DIRPBIT_CDATE :
1842             if (isad) {
1843                 ad_setdate(&ad, AD_DATE_CREATE, cdate);
1844             }
1845             break;
1846         case DIRPBIT_MDATE :
1847             break;
1848         case DIRPBIT_BDATE :
1849             if (isad) {
1850                 ad_setdate(&ad, AD_DATE_BACKUP, bdate);
1851             }
1852             break;
1853         case DIRPBIT_FINFO :
1854             if (isad) {
1855                 /* Fixes #2802236 */
1856                 u_int16_t *fflags = (u_int16_t *)(finder_buf + FINDERINFO_FRFLAGOFF);
1857                 *fflags &= htons(~FINDERINFO_ISHARED);
1858                 /* #2802236 end */
1859                 if (  dir->d_did == DIRDID_ROOT ) {
1860                     /*
1861                      * Alright, we admit it, this is *really* sick!
1862                      * The 4 bytes that we don't copy, when we're dealing
1863                      * with the root of a volume, are the directory's
1864                      * location information. This eliminates that annoying
1865                      * behavior one sees when mounting above another mount
1866                      * point.
1867                      */
1868                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 10 );
1869                     memcpy( ad_entry( &ad, ADEID_FINDERI ) + 14, finder_buf + 14, 18 );
1870                 } else {
1871                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 32 );
1872                 }
1873             }
1874             break;
1875         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1876             if ( (dir->d_did == DIRDID_ROOT) &&
1877                  (setdeskowner( ntohl(owner), -1 ) < 0)) {
1878                 err = set_dir_errors(path, "setdeskowner", errno);
1879                 if (isad && err == AFPERR_PARAM) {
1880                     err = AFP_OK; /* ???*/
1881                 }
1882                 else {
1883                     goto setdirparam_done;
1884                 }
1885             }
1886             if ( setdirowner(vol, upath, ntohl(owner), -1 ) < 0 ) {
1887                 err = set_dir_errors(path, "setdirowner", errno);
1888                 goto setdirparam_done;
1889             }
1890             break;
1891         case DIRPBIT_GID :
1892             if (dir->d_did == DIRDID_ROOT)
1893                 setdeskowner( -1, ntohl(group) );
1894             if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1895                 err = set_dir_errors(path, "setdirowner", errno);
1896                 goto setdirparam_done;
1897             }
1898             break;
1899         case DIRPBIT_ACCESS :
1900             if (dir->d_did == DIRDID_ROOT) {
1901                 setdeskmode(mpriv);
1902                 if (!dir_rx_set(mpriv)) {
1903                     /* we can't remove read and search for owner on volume root */
1904                     err = AFPERR_ACCESS;
1905                     goto setdirparam_done;
1906                 }
1907             }
1908
1909             if (!dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1910                 err = set_dir_errors(path, "setdirmode", errno);
1911                 goto setdirparam_done;
1912             }
1913             break;
1914         case DIRPBIT_PDINFO :
1915             if (afp_version >= 30) {
1916                 err = AFPERR_BITMAP;
1917                 goto setdirparam_done;
1918             }
1919             break;
1920         case DIRPBIT_UNIXPR :
1921             if (vol_unix_priv(vol)) {
1922                 if (dir->d_did == DIRDID_ROOT) {
1923                     if (!dir_rx_set(upriv)) {
1924                         /* we can't remove read and search for owner on volume root */
1925                         err = AFPERR_ACCESS;
1926                         goto setdirparam_done;
1927                     }
1928                     setdeskowner( -1, ntohl(group) );
1929                     setdeskmode( upriv );
1930                 }
1931                 if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1932                     err = set_dir_errors(path, "setdirowner", errno);
1933                     goto setdirparam_done;
1934                 }
1935
1936                 if ( upriv_bit && setdirunixmode(vol, upath, upriv) < 0 ) {
1937                     err = set_dir_errors(path, "setdirunixmode", errno);
1938                     goto setdirparam_done;
1939                 }
1940             }
1941             else {
1942                 err = AFPERR_BITMAP;
1943                 goto setdirparam_done;
1944             }
1945             break;
1946         default :
1947             err = AFPERR_BITMAP;
1948             goto setdirparam_done;
1949             break;
1950         }
1951
1952         bitmap = bitmap>>1;
1953         bit++;
1954     }
1955
1956 setdirparam_done:
1957     if (change_mdate && newdate == 0 && gettimeofday(&tv, NULL) == 0) {
1958         newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
1959     }
1960     if (newdate) {
1961         if (isad)
1962             ad_setdate(&ad, AD_DATE_MODIFY, newdate);
1963         ut.actime = ut.modtime = AD_DATE_TO_UNIX(newdate);
1964         utime(upath, &ut);
1965     }
1966
1967     if ( isad ) {
1968         if (path->st_valid && !path->st_errno) {
1969             struct stat *st = &path->st;
1970
1971             if (dir && dir->d_pdid) {
1972                 ad_setid(&ad, st->st_dev, st->st_ino,  dir->d_did, dir->d_pdid, vol->v_stamp);
1973             }
1974         }
1975         ad_flush( &ad);
1976         ad_close_metadata( &ad);
1977     }
1978
1979     if (change_parent_mdate && dir->d_did != DIRDID_ROOT
1980         && gettimeofday(&tv, NULL) == 0) {
1981         if (movecwd(vol, dirlookup(vol, dir->d_pdid)) == 0) {
1982             newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
1983             /* be careful with bitmap because now dir is null */
1984             bitmap = 1<<DIRPBIT_MDATE;
1985             setdirparams(vol, &Cur_Path, bitmap, (char *)&newdate);
1986             /* should we reset curdir ?*/
1987         }
1988     }
1989
1990     return err;
1991 }
1992
1993 int afp_syncdir(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
1994 {
1995 #ifdef HAVE_DIRFD
1996     DIR                  *dp;
1997 #endif
1998     int                  dfd;
1999     struct vol           *vol;
2000     struct dir           *dir;
2001     u_int32_t            did;
2002     u_int16_t            vid;
2003
2004     *rbuflen = 0;
2005     ibuf += 2;
2006
2007     memcpy( &vid, ibuf, sizeof( vid ));
2008     ibuf += sizeof( vid );
2009     if (NULL == (vol = getvolbyvid( vid )) ) {
2010         return( AFPERR_PARAM );
2011     }
2012
2013     memcpy( &did, ibuf, sizeof( did ));
2014     ibuf += sizeof( did );
2015
2016     /*
2017      * Here's the deal:
2018      * if it's CNID 2 our only choice to meet the specs is call sync.
2019      * For any other CNID just sync that dir. To my knowledge the
2020      * intended use of FPSyncDir is to sync the volume so all we're
2021      * ever going to see here is probably CNID 2. Anyway, we' prepared.
2022      */
2023
2024     if ( ntohl(did) == 2 ) {
2025         sync();
2026     } else {
2027         if (NULL == ( dir = dirlookup( vol, did )) ) {
2028             return afp_errno; /* was AFPERR_NOOBJ */
2029         }
2030
2031         if (movecwd( vol, dir ) < 0 )
2032             return ( AFPERR_NOOBJ );
2033
2034         /*
2035          * Assuming only OSens that have dirfd also may require fsyncing directories
2036          * in order to flush metadata e.g. Linux.
2037          */
2038
2039 #ifdef HAVE_DIRFD
2040         if (NULL == ( dp = opendir( "." )) ) {
2041             switch( errno ) {
2042             case ENOENT :
2043                 return( AFPERR_NOOBJ );
2044             case EACCES :
2045                 return( AFPERR_ACCESS );
2046             default :
2047                 return( AFPERR_PARAM );
2048             }
2049         }
2050
2051         LOG(log_debug, logtype_afpd, "afp_syncdir: dir: '%s'", dir->d_u_name);
2052
2053         dfd = dirfd( dp );
2054         if ( fsync ( dfd ) < 0 )
2055             LOG(log_error, logtype_afpd, "afp_syncdir(%s):  %s",
2056                 dir->d_u_name, strerror(errno) );
2057         closedir(dp); /* closes dfd too */
2058 #endif
2059
2060         if ( -1 == (dfd = open(vol->ad_path(".", ADFLAGS_DIR), O_RDWR))) {
2061             switch( errno ) {
2062             case ENOENT:
2063                 return( AFPERR_NOOBJ );
2064             case EACCES:
2065                 return( AFPERR_ACCESS );
2066             default:
2067                 return( AFPERR_PARAM );
2068             }
2069         }
2070
2071         LOG(log_debug, logtype_afpd, "afp_syncdir: ad-file: '%s'",
2072             vol->ad_path(".", ADFLAGS_DIR) );
2073
2074         if ( fsync(dfd) < 0 )
2075             LOG(log_error, logtype_afpd, "afp_syncdir(%s): %s",
2076                 vol->ad_path(cfrombstring(dir->d_u_name), ADFLAGS_DIR), strerror(errno) );
2077         close(dfd);
2078     }
2079
2080     return ( AFP_OK );
2081 }
2082
2083 int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2084 {
2085     struct adouble  ad;
2086     struct vol      *vol;
2087     struct dir      *dir;
2088     char        *upath;
2089     struct path         *s_path;
2090     u_int32_t       did;
2091     u_int16_t       vid;
2092     int                 err;
2093
2094     *rbuflen = 0;
2095     ibuf += 2;
2096
2097     memcpy( &vid, ibuf, sizeof( vid ));
2098     ibuf += sizeof( vid );
2099     if (NULL == ( vol = getvolbyvid( vid )) ) {
2100         return( AFPERR_PARAM );
2101     }
2102
2103     if (vol->v_flags & AFPVOL_RO)
2104         return AFPERR_VLOCK;
2105
2106     memcpy( &did, ibuf, sizeof( did ));
2107     ibuf += sizeof( did );
2108     if (NULL == ( dir = dirlookup( vol, did )) ) {
2109         return afp_errno; /* was AFPERR_NOOBJ */
2110     }
2111     /* for concurrent access we need to be sure we are not in the
2112      * folder we want to create...
2113      */
2114     movecwd(vol, dir);
2115
2116     if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
2117         return get_afp_errno(AFPERR_PARAM);
2118     }
2119     /* cname was able to move curdir to it! */
2120     if (*s_path->m_name == '\0')
2121         return AFPERR_EXIST;
2122
2123     upath = s_path->u_name;
2124
2125     if (AFP_OK != (err = netatalk_mkdir( upath))) {
2126         return err;
2127     }
2128
2129     if (of_stat(s_path) < 0) {
2130         return AFPERR_MISC;
2131     }
2132
2133     curdir->offcnt++;
2134
2135     if ((dir = dir_add(vol, curdir, s_path, strlen(s_path->u_name))) == NULL) {
2136         return AFPERR_MISC;
2137     }
2138
2139     if ( movecwd( vol, dir ) < 0 ) {
2140         return( AFPERR_PARAM );
2141     }
2142
2143     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2144     if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad ) < 0)  {
2145         if (vol_noadouble(vol))
2146             goto createdir_done;
2147         return( AFPERR_ACCESS );
2148     }
2149     ad_setname(&ad, s_path->m_name);
2150     ad_setid( &ad, s_path->st.st_dev, s_path->st.st_ino, dir->d_did, did, vol->v_stamp);
2151
2152     ad_flush( &ad);
2153     ad_close_metadata( &ad);
2154
2155 createdir_done:
2156 #ifdef HAVE_NFSv4_ACLS
2157     /* FIXME: are we really inside the created dir? */
2158     addir_inherit_acl(vol);
2159 #endif
2160
2161     memcpy( rbuf, &dir->d_did, sizeof( u_int32_t ));
2162     *rbuflen = sizeof( u_int32_t );
2163     setvoltime(obj, vol );
2164     return( AFP_OK );
2165 }
2166
2167 /*
2168  * dst       new unix filename (not a pathname)
2169  * newname   new mac name
2170  * newparent curdir
2171  */
2172 int renamedir(const struct vol *vol, char *src, char *dst,
2173               struct dir *dir,
2174               struct dir *newparent,
2175               char *newname)
2176 {
2177     struct adouble  ad;
2178     int             err;
2179
2180     /* existence check moved to afp_moveandrename */
2181     if ( unix_rename( src, dst ) < 0 ) {
2182         switch ( errno ) {
2183         case ENOENT :
2184             return( AFPERR_NOOBJ );
2185         case EACCES :
2186             return( AFPERR_ACCESS );
2187         case EROFS:
2188             return AFPERR_VLOCK;
2189         case EINVAL:
2190             /* tried to move directory into a subdirectory of itself */
2191             return AFPERR_CANTMOVE;
2192         case EXDEV:
2193             /* this needs to copy and delete. bleah. that means we have
2194              * to deal with entire directory hierarchies. */
2195             if ((err = copydir(vol, src, dst)) < 0) {
2196                 deletedir(dst);
2197                 return err;
2198             }
2199             if ((err = deletedir(src)) < 0)
2200                 return err;
2201             break;
2202         default :
2203             return( AFPERR_PARAM );
2204         }
2205     }
2206
2207     vol->vfs->vfs_renamedir(vol, src, dst);
2208
2209     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2210
2211     if (!ad_open_metadata( dst, ADFLAGS_DIR, 0, &ad)) {
2212         ad_setname(&ad, newname);
2213         ad_flush( &ad);
2214         ad_close_metadata( &ad);
2215     }
2216
2217     if (dir_modify(vol, dir, curdir->d_did, 0, newname, dst, curdir->d_fullpath) != 0) {
2218         LOG(log_error, logtype_afpd, "renamedir: fatal error from dir_modify: %s -> %s", src, dst);
2219         return AFPERR_MISC;
2220     }
2221
2222     return( AFP_OK );
2223 }
2224
2225 /* delete an empty directory */
2226 int deletecurdir(struct vol *vol)
2227 {
2228     struct dirent *de;
2229     struct stat st;
2230     struct dir  *fdir;
2231     DIR *dp;
2232     struct adouble  ad;
2233     u_int16_t       ashort;
2234     int err;
2235
2236     if ( dirlookup(vol, curdir->d_pdid) == NULL ) {
2237         return( AFPERR_ACCESS );
2238     }
2239
2240     fdir = curdir;
2241
2242     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2243     /* we never want to create a resource fork here, we are going to delete it */
2244     if ( ad_metadata( ".", ADFLAGS_DIR, &ad) == 0 ) {
2245
2246         ad_getattr(&ad, &ashort);
2247         ad_close( &ad, ADFLAGS_HF );
2248         if ((ashort & htons(ATTRBIT_NODELETE))) {
2249             return  AFPERR_OLOCK;
2250         }
2251     }
2252     err = vol->vfs->vfs_deletecurdir(vol);
2253     if (err) {
2254         return err;
2255     }
2256
2257     /* now get rid of dangling symlinks */
2258     if ((dp = opendir("."))) {
2259         while ((de = readdir(dp))) {
2260             /* skip this and previous directory */
2261             if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
2262                 continue;
2263
2264             /* bail if it's not a symlink */
2265             if ((lstat(de->d_name, &st) == 0) && !S_ISLNK(st.st_mode)) {
2266                 closedir(dp);
2267                 return AFPERR_DIRNEMPT;
2268             }
2269
2270             if ((err = netatalk_unlink(de->d_name))) {
2271                 closedir(dp);
2272                 return err;
2273             }
2274         }
2275     }
2276
2277     if ( movecwd(vol, dirlookup(vol, curdir->d_pdid)) < 0 ) {
2278         err = afp_errno;
2279         goto delete_done;
2280     }
2281
2282     err = netatalk_rmdir_all_errors(cfrombstring(fdir->d_u_name));
2283     if ( err ==  AFP_OK || err == AFPERR_NOOBJ) {
2284         cnid_delete(vol->v_cdb, fdir->d_did);
2285         dir_remove( vol, fdir );
2286     }
2287 delete_done:
2288     if (dp) {
2289         /* inode is used as key for cnid.
2290          * Close the descriptor only after cnid_delete
2291          * has been called.
2292          */
2293         closedir(dp);
2294     }
2295     return err;
2296 }
2297
2298 int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2299 {
2300     struct passwd   *pw;
2301     struct group    *gr;
2302     char        *name;
2303     u_int32_t           id;
2304     int         len, sfunc;
2305     int         utf8 = 0;
2306
2307     ibuf++;
2308     sfunc = (unsigned char) *ibuf++;
2309     *rbuflen = 0;
2310
2311
2312     if (sfunc >= 3 && sfunc <= 6) {
2313         if (afp_version < 30) {
2314             return( AFPERR_PARAM );
2315         }
2316         utf8 = 1;
2317     }
2318
2319     switch ( sfunc ) {
2320     case 1 :
2321     case 3 :/* unicode */
2322         memcpy( &id, ibuf, sizeof( id ));
2323         id = ntohl(id);
2324         if ( id != 0 ) {
2325             if (( pw = getpwuid( id )) == NULL ) {
2326                 return( AFPERR_NOITEM );
2327             }
2328             len = convert_string_allocate( obj->options.unixcharset, ((!utf8)?obj->options.maccharset:CH_UTF8_MAC),
2329                                            pw->pw_name, -1, &name);
2330         } else {
2331             len = 0;
2332             name = NULL;
2333         }
2334         break;
2335     case 2 :
2336     case 4 : /* unicode */
2337         memcpy( &id, ibuf, sizeof( id ));
2338         id = ntohl(id);
2339         if ( id != 0 ) {
2340             if (NULL == ( gr = (struct group *)getgrgid( id ))) {
2341                 return( AFPERR_NOITEM );
2342             }
2343             len = convert_string_allocate( obj->options.unixcharset, (!utf8)?obj->options.maccharset:CH_UTF8_MAC,
2344                                            gr->gr_name, -1, &name);
2345         } else {
2346             len = 0;
2347             name = NULL;
2348         }
2349         break;
2350 #ifdef HAVE_NFSv4_ACLS
2351     case 5 : /* UUID -> username */
2352     case 6 : /* UUID -> groupname */
2353         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2354             return AFPERR_PARAM;
2355         LOG(log_debug, logtype_afpd, "afp_mapid: valid UUID request");
2356         uuidtype_t type;
2357         len = getnamefromuuid( ibuf, &name, &type);
2358         if (len != 0)       /* its a error code, not len */
2359             return AFPERR_NOITEM;
2360         if (type == UUID_USER) {
2361             if (( pw = getpwnam( name )) == NULL )
2362                 return( AFPERR_NOITEM );
2363             LOG(log_debug, logtype_afpd, "afp_mapid: name:%s -> uid:%d", name, pw->pw_uid);
2364             id = htonl(UUID_USER);
2365             memcpy( rbuf, &id, sizeof( id ));
2366             id = htonl( pw->pw_uid);
2367             rbuf += sizeof( id );
2368             memcpy( rbuf, &id, sizeof( id ));
2369             rbuf += sizeof( id );
2370             *rbuflen = 2 * sizeof( id );
2371         } else {        /* type == UUID_GROUP */
2372             if (( gr = getgrnam( name )) == NULL )
2373                 return( AFPERR_NOITEM );
2374             LOG(log_debug, logtype_afpd, "afp_mapid: group:%s -> gid:%d", name, gr->gr_gid);
2375             id = htonl(UUID_GROUP);
2376             memcpy( rbuf, &id, sizeof( id ));
2377             rbuf += sizeof( id );
2378             id = htonl( gr->gr_gid);
2379             memcpy( rbuf, &id, sizeof( id ));
2380             rbuf += sizeof( id );
2381             *rbuflen = 2 * sizeof( id );
2382         }
2383         break;
2384 #endif
2385     default :
2386         return( AFPERR_PARAM );
2387     }
2388
2389     if (name)
2390         len = strlen( name );
2391
2392     if (utf8) {
2393         u_int16_t tp = htons(len);
2394         memcpy(rbuf, &tp, sizeof(tp));
2395         rbuf += sizeof(tp);
2396         *rbuflen += 2;
2397     }
2398     else {
2399         *rbuf++ = len;
2400         *rbuflen += 1;
2401     }
2402     if ( len > 0 ) {
2403         memcpy( rbuf, name, len );
2404     }
2405     *rbuflen += len;
2406     if (name)
2407         free(name);
2408     return( AFP_OK );
2409 }
2410
2411 int afp_mapname(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2412 {
2413     struct passwd   *pw;
2414     struct group    *gr;
2415     int             len, sfunc;
2416     u_int32_t       id;
2417     u_int16_t       ulen;
2418
2419     ibuf++;
2420     sfunc = (unsigned char) *ibuf++;
2421     *rbuflen = 0;
2422     LOG(log_debug, logtype_afpd, "afp_mapname: sfunc: %d, afp_version: %d", sfunc, afp_version);
2423     switch ( sfunc ) {
2424     case 1 :
2425     case 2 : /* unicode */
2426         if (afp_version < 30) {
2427             return( AFPERR_PARAM );
2428         }
2429         memcpy(&ulen, ibuf, sizeof(ulen));
2430         len = ntohs(ulen);
2431         ibuf += 2;
2432         LOG(log_debug, logtype_afpd, "afp_mapname: alive");
2433         break;
2434     case 3 :
2435     case 4 :
2436         len = (unsigned char) *ibuf++;
2437         break;
2438 #ifdef HAVE_NFSv4_ACLS
2439     case 5 : /* username -> UUID  */
2440     case 6 : /* groupname -> UUID */
2441         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2442             return AFPERR_PARAM;
2443         memcpy(&ulen, ibuf, sizeof(ulen));
2444         len = ntohs(ulen);
2445         ibuf += 2;
2446         break;
2447 #endif
2448     default :
2449         return( AFPERR_PARAM );
2450     }
2451
2452     ibuf[ len ] = '\0';
2453
2454     if ( len == 0 )
2455         return AFPERR_PARAM;
2456     else {
2457         switch ( sfunc ) {
2458         case 1 : /* unicode */
2459         case 3 :
2460             if (NULL == ( pw = (struct passwd *)getpwnam( ibuf )) ) {
2461                 return( AFPERR_NOITEM );
2462             }
2463             id = pw->pw_uid;
2464             id = htonl(id);
2465             memcpy( rbuf, &id, sizeof( id ));
2466             *rbuflen = sizeof( id );
2467             break;
2468
2469         case 2 : /* unicode */
2470         case 4 :
2471             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s",ibuf);
2472             if (NULL == ( gr = (struct group *)getgrnam( ibuf ))) {
2473                 return( AFPERR_NOITEM );
2474             }
2475             id = gr->gr_gid;
2476             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s -> id: %d",ibuf, id);
2477             id = htonl(id);
2478             memcpy( rbuf, &id, sizeof( id ));
2479             *rbuflen = sizeof( id );
2480             break;
2481 #ifdef HAVE_NFSv4_ACLS
2482         case 5 :        /* username -> UUID */
2483             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2484             if (0 != getuuidfromname(ibuf, UUID_USER, rbuf))
2485                 return AFPERR_NOITEM;
2486             *rbuflen = UUID_BINSIZE;
2487             break;
2488         case 6 :        /* groupname -> UUID */
2489             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2490             if (0 != getuuidfromname(ibuf, UUID_GROUP, rbuf))
2491                 return AFPERR_NOITEM;
2492             *rbuflen = UUID_BINSIZE;
2493             break;
2494 #endif
2495         }
2496     }
2497     return( AFP_OK );
2498 }
2499
2500 /* ------------------------------------
2501    variable DID support
2502 */
2503 int afp_closedir(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2504 {
2505 #if 0
2506     struct vol   *vol;
2507     struct dir   *dir;
2508     u_int16_t    vid;
2509     u_int32_t    did;
2510 #endif /* 0 */
2511
2512     *rbuflen = 0;
2513
2514     /* do nothing as dids are static for the life of the process. */
2515 #if 0
2516     ibuf += 2;
2517
2518     memcpy(&vid,  ibuf, sizeof( vid ));
2519     ibuf += sizeof( vid );
2520     if (( vol = getvolbyvid( vid )) == NULL ) {
2521         return( AFPERR_PARAM );
2522     }
2523
2524     memcpy( &did, ibuf, sizeof( did ));
2525     ibuf += sizeof( did );
2526     if (( dir = dirlookup( vol, did )) == NULL ) {
2527         return( AFPERR_PARAM );
2528     }
2529
2530     /* dir_remove -- deletedid */
2531 #endif /* 0 */
2532
2533     return AFP_OK;
2534 }
2535
2536 /* did creation gets done automatically
2537  * there's a pb again with case but move it to cname
2538  */
2539 int afp_opendir(AFPObj *obj _U_, char *ibuf, size_t ibuflen  _U_, char *rbuf, size_t *rbuflen)
2540 {
2541     struct vol      *vol;
2542     struct dir      *parentdir;
2543     struct path     *path;
2544     u_int32_t       did;
2545     u_int16_t       vid;
2546
2547     *rbuflen = 0;
2548     ibuf += 2;
2549
2550     memcpy(&vid, ibuf, sizeof(vid));
2551     ibuf += sizeof( vid );
2552
2553     if (NULL == ( vol = getvolbyvid( vid )) ) {
2554         return( AFPERR_PARAM );
2555     }
2556
2557     memcpy(&did, ibuf, sizeof(did));
2558     ibuf += sizeof(did);
2559
2560     if (NULL == ( parentdir = dirlookup( vol, did )) ) {
2561         return afp_errno;
2562     }
2563
2564     if (NULL == ( path = cname( vol, parentdir, &ibuf )) ) {
2565         return get_afp_errno(AFPERR_PARAM);
2566     }
2567
2568     if ( *path->m_name != '\0' ) {
2569         return path_error(path, AFPERR_NOOBJ);
2570     }
2571
2572     if ( !path->st_valid && of_stat(path ) < 0 ) {
2573         return( AFPERR_NOOBJ );
2574     }
2575     if ( path->st_errno ) {
2576         return( AFPERR_NOOBJ );
2577     }
2578
2579     memcpy(rbuf, &curdir->d_did, sizeof(curdir->d_did));
2580     *rbuflen = sizeof(curdir->d_did);
2581     return AFP_OK;
2582 }