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