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