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