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