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