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