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