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