]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/directory.c
Fix ACL permission mapping
[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 = 0;
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[UTF8FILELEN_EARLY]) {   /* FIXME safeguard, limit of early Mac OS X */
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
1332     LOG(log_debug, logtype_afpd, "file_access(\"%s\"): mapped user mode: 0x%02x",
1333         path->u_name, ma.ma_user);
1334
1335     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE)) {
1336         LOG(log_debug, logtype_afpd, "file_access(\"%s\"): write access denied", path->u_name);
1337         return -1;
1338     }
1339     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD)) {
1340         LOG(log_debug, logtype_afpd, "file_access(\"%s\"): read access denied", path->u_name);
1341         return -1;
1342     }
1343     return 0;
1344
1345 }
1346
1347 /* --------------------- */
1348 void setdiroffcnt(struct dir *dir, struct stat *st,  u_int32_t count)
1349 {
1350     dir->offcnt = count;
1351     dir->ctime = st->st_ctime;
1352     dir->d_flags &= ~DIRF_CNID;
1353 }
1354
1355
1356 /* ---------------------
1357  * is our cached also for reenumerate id?
1358  */
1359 int dirreenumerate(struct dir *dir, struct stat *st)
1360 {
1361     return st->st_ctime == dir->ctime && (dir->d_flags & DIRF_CNID);
1362 }
1363
1364 /* ------------------------------
1365    (".", curdir)
1366    (name, dir) with curdir:name == dir, from afp_enumerate
1367 */
1368
1369 int getdirparams(const struct vol *vol,
1370                  u_int16_t bitmap, struct path *s_path,
1371                  struct dir *dir,
1372                  char *buf, size_t *buflen )
1373 {
1374     struct maccess  ma;
1375     struct adouble  ad;
1376     char        *data, *l_nameoff = NULL, *utf_nameoff = NULL;
1377     int         bit = 0, isad = 0;
1378     u_int32_t           aint;
1379     u_int16_t       ashort;
1380     int                 ret;
1381     u_int32_t           utf8 = 0;
1382     cnid_t              pdid;
1383     struct stat *st = &s_path->st;
1384     char *upath = s_path->u_name;
1385
1386     if ((bitmap & ((1 << DIRPBIT_ATTR)  |
1387                    (1 << DIRPBIT_CDATE) |
1388                    (1 << DIRPBIT_MDATE) |
1389                    (1 << DIRPBIT_BDATE) |
1390                    (1 << DIRPBIT_FINFO)))) {
1391
1392         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1393         if ( !ad_metadata( upath, ADFLAGS_CREATE|ADFLAGS_DIR, &ad) ) {
1394             isad = 1;
1395             if (ad.ad_md->adf_flags & O_CREAT) {
1396                 /* We just created it */
1397                 ad_setname(&ad, s_path->m_name);
1398                 ad_setid( &ad,
1399                           s_path->st.st_dev,
1400                           s_path->st.st_ino,
1401                           dir->d_did,
1402                           dir->d_pdid,
1403                           vol->v_stamp);
1404                 ad_flush( &ad);
1405             }
1406         }
1407     }
1408
1409     pdid = dir->d_pdid;
1410
1411     data = buf;
1412     while ( bitmap != 0 ) {
1413         while (( bitmap & 1 ) == 0 ) {
1414             bitmap = bitmap>>1;
1415             bit++;
1416         }
1417
1418         switch ( bit ) {
1419         case DIRPBIT_ATTR :
1420             if ( isad ) {
1421                 ad_getattr(&ad, &ashort);
1422             } else if (invisible_dots(vol, cfrombstr(dir->d_u_name))) {
1423                 ashort = htons(ATTRBIT_INVISIBLE);
1424             } else
1425                 ashort = 0;
1426             ashort |= htons(ATTRBIT_SHARED);
1427             memcpy( data, &ashort, sizeof( ashort ));
1428             data += sizeof( ashort );
1429             break;
1430
1431         case DIRPBIT_PDID :
1432             memcpy( data, &pdid, sizeof( pdid ));
1433             data += sizeof( pdid );
1434             LOG(log_debug, logtype_afpd, "metadata('%s'):     Parent DID: %u",
1435                 s_path->u_name, ntohl(pdid));
1436             break;
1437
1438         case DIRPBIT_CDATE :
1439             if (!isad || (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0))
1440                 aint = AD_DATE_FROM_UNIX(st->st_mtime);
1441             memcpy( data, &aint, sizeof( aint ));
1442             data += sizeof( aint );
1443             break;
1444
1445         case DIRPBIT_MDATE :
1446             aint = AD_DATE_FROM_UNIX(st->st_mtime);
1447             memcpy( data, &aint, sizeof( aint ));
1448             data += sizeof( aint );
1449             break;
1450
1451         case DIRPBIT_BDATE :
1452             if (!isad || (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1453                 aint = AD_DATE_START;
1454             memcpy( data, &aint, sizeof( aint ));
1455             data += sizeof( aint );
1456             break;
1457
1458         case DIRPBIT_FINFO :
1459             if ( isad ) {
1460                 memcpy( data, ad_entry( &ad, ADEID_FINDERI ), 32 );
1461             } else { /* no appledouble */
1462                 memset( data, 0, 32 );
1463                 /* set default view -- this also gets done in ad_open() */
1464                 ashort = htons(FINDERINFO_CLOSEDVIEW);
1465                 memcpy(data + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
1466
1467                 /* dot files are by default visible */
1468                 if (invisible_dots(vol, cfrombstr(dir->d_u_name))) {
1469                     ashort = htons(FINDERINFO_INVISIBLE);
1470                     memcpy(data + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
1471                 }
1472             }
1473             data += 32;
1474             break;
1475
1476         case DIRPBIT_LNAME :
1477             if (dir->d_m_name) /* root of parent can have a null name */
1478                 l_nameoff = data;
1479             else
1480                 memset(data, 0, sizeof(u_int16_t));
1481             data += sizeof( u_int16_t );
1482             break;
1483
1484         case DIRPBIT_SNAME :
1485             memset(data, 0, sizeof(u_int16_t));
1486             data += sizeof( u_int16_t );
1487             break;
1488
1489         case DIRPBIT_DID :
1490             memcpy( data, &dir->d_did, sizeof( aint ));
1491             data += sizeof( aint );
1492             LOG(log_debug, logtype_afpd, "metadata('%s'):            DID: %u",
1493                 s_path->u_name, ntohl(dir->d_did));
1494             break;
1495
1496         case DIRPBIT_OFFCNT :
1497             ashort = 0;
1498             /* this needs to handle current directory access rights */
1499             if (diroffcnt(dir, st)) {
1500                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1501             }
1502             else if ((ret = for_each_dirent(vol, upath, NULL,NULL)) >= 0) {
1503                 setdiroffcnt(dir, st,  ret);
1504                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1505             }
1506             ashort = htons( ashort );
1507             memcpy( data, &ashort, sizeof( ashort ));
1508             data += sizeof( ashort );
1509             break;
1510
1511         case DIRPBIT_UID :
1512             aint = htonl(st->st_uid);
1513             memcpy( data, &aint, sizeof( aint ));
1514             data += sizeof( aint );
1515             break;
1516
1517         case DIRPBIT_GID :
1518             aint = htonl(st->st_gid);
1519             memcpy( data, &aint, sizeof( aint ));
1520             data += sizeof( aint );
1521             break;
1522
1523         case DIRPBIT_ACCESS :
1524             accessmode( upath, &ma, dir , st);
1525
1526             *data++ = ma.ma_user;
1527             *data++ = ma.ma_world;
1528             *data++ = ma.ma_group;
1529             *data++ = ma.ma_owner;
1530             break;
1531
1532             /* Client has requested the ProDOS information block.
1533                Just pass back the same basic block for all
1534                directories. <shirsch@ibm.net> */
1535         case DIRPBIT_PDINFO :
1536             if (afp_version >= 30) { /* UTF8 name */
1537                 utf8 = kTextEncodingUTF8;
1538                 if (dir->d_m_name) /* root of parent can have a null name */
1539                     utf_nameoff = data;
1540                 else
1541                     memset(data, 0, sizeof(u_int16_t));
1542                 data += sizeof( u_int16_t );
1543                 aint = 0;
1544                 memcpy(data, &aint, sizeof( aint ));
1545                 data += sizeof( aint );
1546             }
1547             else { /* ProDOS Info Block */
1548                 *data++ = 0x0f;
1549                 *data++ = 0;
1550                 ashort = htons( 0x0200 );
1551                 memcpy( data, &ashort, sizeof( ashort ));
1552                 data += sizeof( ashort );
1553                 memset( data, 0, sizeof( ashort ));
1554                 data += sizeof( ashort );
1555             }
1556             break;
1557
1558         case DIRPBIT_UNIXPR :
1559             aint = htonl(st->st_uid);
1560             memcpy( data, &aint, sizeof( aint ));
1561             data += sizeof( aint );
1562             aint = htonl(st->st_gid);
1563             memcpy( data, &aint, sizeof( aint ));
1564             data += sizeof( aint );
1565
1566             aint = st->st_mode;
1567             aint = htonl ( aint & ~S_ISGID );  /* Remove SGID, OSX doesn't like it ... */
1568             memcpy( data, &aint, sizeof( aint ));
1569             data += sizeof( aint );
1570
1571             accessmode( upath, &ma, dir , st);
1572
1573             *data++ = ma.ma_user;
1574             *data++ = ma.ma_world;
1575             *data++ = ma.ma_group;
1576             *data++ = ma.ma_owner;
1577             break;
1578
1579         default :
1580             if ( isad ) {
1581                 ad_close_metadata( &ad );
1582             }
1583             return( AFPERR_BITMAP );
1584         }
1585         bitmap = bitmap>>1;
1586         bit++;
1587     }
1588     if ( l_nameoff ) {
1589         ashort = htons( data - buf );
1590         memcpy( l_nameoff, &ashort, sizeof( ashort ));
1591         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, 0);
1592     }
1593     if ( utf_nameoff ) {
1594         ashort = htons( data - buf );
1595         memcpy( utf_nameoff, &ashort, sizeof( ashort ));
1596         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, utf8);
1597     }
1598     if ( isad ) {
1599         ad_close_metadata( &ad );
1600     }
1601     *buflen = data - buf;
1602     return( AFP_OK );
1603 }
1604
1605 /* ----------------------------- */
1606 int path_error(struct path *path, int error)
1607 {
1608 /* - a dir with access error
1609  * - no error it's a file
1610  * - file not found
1611  */
1612     if (path_isadir(path))
1613         return afp_errno;
1614     if (path->st_valid && path->st_errno)
1615         return error;
1616     return AFPERR_BADTYPE ;
1617 }
1618
1619 /* ----------------------------- */
1620 int afp_setdirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
1621 {
1622     struct vol  *vol;
1623     struct dir  *dir;
1624     struct path *path;
1625     u_int16_t   vid, bitmap;
1626     u_int32_t   did;
1627     int     rc;
1628
1629     *rbuflen = 0;
1630     ibuf += 2;
1631     memcpy( &vid, ibuf, sizeof( vid ));
1632     ibuf += sizeof( vid );
1633
1634     if (NULL == ( vol = getvolbyvid( vid )) ) {
1635         return( AFPERR_PARAM );
1636     }
1637
1638     if (vol->v_flags & AFPVOL_RO)
1639         return AFPERR_VLOCK;
1640
1641     memcpy( &did, ibuf, sizeof( did ));
1642     ibuf += sizeof( int );
1643
1644     if (NULL == ( dir = dirlookup( vol, did )) ) {
1645         return afp_errno;
1646     }
1647
1648     memcpy( &bitmap, ibuf, sizeof( bitmap ));
1649     bitmap = ntohs( bitmap );
1650     ibuf += sizeof( bitmap );
1651
1652     if (NULL == ( path = cname( vol, dir, &ibuf )) ) {
1653         return get_afp_errno(AFPERR_NOOBJ);
1654     }
1655
1656     if ( *path->m_name != '\0' ) {
1657         rc = path_error(path, AFPERR_NOOBJ);
1658         /* maybe we are trying to set perms back */
1659         if (rc != AFPERR_ACCESS)
1660             return rc;
1661     }
1662
1663     /*
1664      * If ibuf is odd, make it even.
1665      */
1666     if ((u_long)ibuf & 1 ) {
1667         ibuf++;
1668     }
1669
1670     if (AFP_OK == ( rc = setdirparams(vol, path, bitmap, ibuf )) ) {
1671         setvoltime(obj, vol );
1672     }
1673     return( rc );
1674 }
1675
1676 /*
1677  * cf AFP3.0.pdf page 244 for change_mdate and change_parent_mdate logic
1678  *
1679  * assume path == '\0' eg. it's a directory in canonical form
1680  */
1681 int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *buf )
1682 {
1683     struct maccess  ma;
1684     struct adouble  ad;
1685     struct utimbuf      ut;
1686     struct timeval      tv;
1687
1688     char                *upath;
1689     struct dir          *dir;
1690     int         bit, isad = 1;
1691     int                 cdate, bdate;
1692     int                 owner, group;
1693     u_int16_t       ashort, bshort, oshort;
1694     int                 err = AFP_OK;
1695     int                 change_mdate = 0;
1696     int                 change_parent_mdate = 0;
1697     int                 newdate = 0;
1698     u_int16_t           bitmap = d_bitmap;
1699     u_char              finder_buf[32];
1700     u_int32_t       upriv;
1701     mode_t              mpriv = 0;
1702     u_int16_t           upriv_bit = 0;
1703
1704     bit = 0;
1705     upath = path->u_name;
1706     dir   = path->d_dir;
1707     while ( bitmap != 0 ) {
1708         while (( bitmap & 1 ) == 0 ) {
1709             bitmap = bitmap>>1;
1710             bit++;
1711         }
1712
1713         switch( bit ) {
1714         case DIRPBIT_ATTR :
1715             change_mdate = 1;
1716             memcpy( &ashort, buf, sizeof( ashort ));
1717             buf += sizeof( ashort );
1718             break;
1719         case DIRPBIT_CDATE :
1720             change_mdate = 1;
1721             memcpy(&cdate, buf, sizeof(cdate));
1722             buf += sizeof( cdate );
1723             break;
1724         case DIRPBIT_MDATE :
1725             memcpy(&newdate, buf, sizeof(newdate));
1726             buf += sizeof( newdate );
1727             break;
1728         case DIRPBIT_BDATE :
1729             change_mdate = 1;
1730             memcpy(&bdate, buf, sizeof(bdate));
1731             buf += sizeof( bdate );
1732             break;
1733         case DIRPBIT_FINFO :
1734             change_mdate = 1;
1735             memcpy( finder_buf, buf, 32 );
1736             buf += 32;
1737             break;
1738         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1739             change_parent_mdate = 1;
1740             memcpy( &owner, buf, sizeof(owner));
1741             buf += sizeof( owner );
1742             break;
1743         case DIRPBIT_GID :
1744             change_parent_mdate = 1;
1745             memcpy( &group, buf, sizeof( group ));
1746             buf += sizeof( group );
1747             break;
1748         case DIRPBIT_ACCESS :
1749             change_mdate = 1;
1750             change_parent_mdate = 1;
1751             ma.ma_user = *buf++;
1752             ma.ma_world = *buf++;
1753             ma.ma_group = *buf++;
1754             ma.ma_owner = *buf++;
1755             mpriv = mtoumode( &ma ) | vol->v_dperm;
1756             if (dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1757                 err = set_dir_errors(path, "setdirmode", errno);
1758                 bitmap = 0;
1759             }
1760             break;
1761             /* Ignore what the client thinks we should do to the
1762                ProDOS information block.  Skip over the data and
1763                report nothing amiss. <shirsch@ibm.net> */
1764         case DIRPBIT_PDINFO :
1765             if (afp_version < 30) {
1766                 buf += 6;
1767             }
1768             else {
1769                 err = AFPERR_BITMAP;
1770                 bitmap = 0;
1771             }
1772             break;
1773         case DIRPBIT_UNIXPR :
1774             if (vol_unix_priv(vol)) {
1775                 memcpy( &owner, buf, sizeof(owner)); /* FIXME need to change owner too? */
1776                 buf += sizeof( owner );
1777                 memcpy( &group, buf, sizeof( group ));
1778                 buf += sizeof( group );
1779
1780                 change_mdate = 1;
1781                 change_parent_mdate = 1;
1782                 memcpy( &upriv, buf, sizeof( upriv ));
1783                 buf += sizeof( upriv );
1784                 upriv = ntohl (upriv) | vol->v_dperm;
1785                 if (dir_rx_set(upriv)) {
1786                     /* maybe we are trying to set perms back */
1787                     if ( setdirunixmode(vol, upath, upriv) < 0 ) {
1788                         bitmap = 0;
1789                         err = set_dir_errors(path, "setdirunixmode", errno);
1790                     }
1791                 }
1792                 else {
1793                     /* do it later */
1794                     upriv_bit = 1;
1795                 }
1796                 break;
1797             }
1798             /* fall through */
1799         default :
1800             err = AFPERR_BITMAP;
1801             bitmap = 0;
1802             break;
1803         }
1804
1805         bitmap = bitmap>>1;
1806         bit++;
1807     }
1808     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1809
1810     if (ad_open_metadata( upath, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
1811         /*
1812          * Check to see what we're trying to set.  If it's anything
1813          * but ACCESS, UID, or GID, give an error.  If it's any of those
1814          * three, we don't need the ad to be open, so just continue.
1815          *
1816          * note: we also don't need to worry about mdate. also, be quiet
1817          *       if we're using the noadouble option.
1818          */
1819         if (!vol_noadouble(vol) && (d_bitmap &
1820                                     ~((1<<DIRPBIT_ACCESS)|(1<<DIRPBIT_UNIXPR)|
1821                                       (1<<DIRPBIT_UID)|(1<<DIRPBIT_GID)|
1822                                       (1<<DIRPBIT_MDATE)|(1<<DIRPBIT_PDINFO)))) {
1823             return AFPERR_ACCESS;
1824         }
1825
1826         isad = 0;
1827     } else {
1828         /*
1829          * Check to see if a create was necessary. If it was, we'll want
1830          * to set our name, etc.
1831          */
1832         if ( (ad_get_HF_flags( &ad ) & O_CREAT)) {
1833             ad_setname(&ad, cfrombstr(curdir->d_m_name));
1834         }
1835     }
1836
1837     bit = 0;
1838     bitmap = d_bitmap;
1839     while ( bitmap != 0 ) {
1840         while (( bitmap & 1 ) == 0 ) {
1841             bitmap = bitmap>>1;
1842             bit++;
1843         }
1844
1845         switch( bit ) {
1846         case DIRPBIT_ATTR :
1847             if (isad) {
1848                 ad_getattr(&ad, &bshort);
1849                 oshort = bshort;
1850                 if ( ntohs( ashort ) & ATTRBIT_SETCLR ) {
1851                     bshort |= htons( ntohs( ashort ) & ~ATTRBIT_SETCLR );
1852                 } else {
1853                     bshort &= ~ashort;
1854                 }
1855                 if ((bshort & htons(ATTRBIT_INVISIBLE)) != (oshort & htons(ATTRBIT_INVISIBLE)))
1856                     change_parent_mdate = 1;
1857                 ad_setattr(&ad, bshort);
1858             }
1859             break;
1860         case DIRPBIT_CDATE :
1861             if (isad) {
1862                 ad_setdate(&ad, AD_DATE_CREATE, cdate);
1863             }
1864             break;
1865         case DIRPBIT_MDATE :
1866             break;
1867         case DIRPBIT_BDATE :
1868             if (isad) {
1869                 ad_setdate(&ad, AD_DATE_BACKUP, bdate);
1870             }
1871             break;
1872         case DIRPBIT_FINFO :
1873             if (isad) {
1874                 /* Fixes #2802236 */
1875                 u_int16_t *fflags = (u_int16_t *)(finder_buf + FINDERINFO_FRFLAGOFF);
1876                 *fflags &= htons(~FINDERINFO_ISHARED);
1877                 /* #2802236 end */
1878                 if (  dir->d_did == DIRDID_ROOT ) {
1879                     /*
1880                      * Alright, we admit it, this is *really* sick!
1881                      * The 4 bytes that we don't copy, when we're dealing
1882                      * with the root of a volume, are the directory's
1883                      * location information. This eliminates that annoying
1884                      * behavior one sees when mounting above another mount
1885                      * point.
1886                      */
1887                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 10 );
1888                     memcpy( ad_entry( &ad, ADEID_FINDERI ) + 14, finder_buf + 14, 18 );
1889                 } else {
1890                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 32 );
1891                 }
1892             }
1893             break;
1894         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1895             if ( (dir->d_did == DIRDID_ROOT) &&
1896                  (setdeskowner( ntohl(owner), -1 ) < 0)) {
1897                 err = set_dir_errors(path, "setdeskowner", errno);
1898                 if (isad && err == AFPERR_PARAM) {
1899                     err = AFP_OK; /* ???*/
1900                 }
1901                 else {
1902                     goto setdirparam_done;
1903                 }
1904             }
1905             if ( setdirowner(vol, upath, ntohl(owner), -1 ) < 0 ) {
1906                 err = set_dir_errors(path, "setdirowner", errno);
1907                 goto setdirparam_done;
1908             }
1909             break;
1910         case DIRPBIT_GID :
1911             if (dir->d_did == DIRDID_ROOT)
1912                 setdeskowner( -1, ntohl(group) );
1913             if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1914                 err = set_dir_errors(path, "setdirowner", errno);
1915                 goto setdirparam_done;
1916             }
1917             break;
1918         case DIRPBIT_ACCESS :
1919             if (dir->d_did == DIRDID_ROOT) {
1920                 setdeskmode(mpriv);
1921                 if (!dir_rx_set(mpriv)) {
1922                     /* we can't remove read and search for owner on volume root */
1923                     err = AFPERR_ACCESS;
1924                     goto setdirparam_done;
1925                 }
1926             }
1927
1928             if (!dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1929                 err = set_dir_errors(path, "setdirmode", errno);
1930                 goto setdirparam_done;
1931             }
1932             break;
1933         case DIRPBIT_PDINFO :
1934             if (afp_version >= 30) {
1935                 err = AFPERR_BITMAP;
1936                 goto setdirparam_done;
1937             }
1938             break;
1939         case DIRPBIT_UNIXPR :
1940             if (vol_unix_priv(vol)) {
1941                 if (dir->d_did == DIRDID_ROOT) {
1942                     if (!dir_rx_set(upriv)) {
1943                         /* we can't remove read and search for owner on volume root */
1944                         err = AFPERR_ACCESS;
1945                         goto setdirparam_done;
1946                     }
1947                     setdeskowner( -1, ntohl(group) );
1948                     setdeskmode( upriv );
1949                 }
1950                 if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1951                     err = set_dir_errors(path, "setdirowner", errno);
1952                     goto setdirparam_done;
1953                 }
1954
1955                 if ( upriv_bit && setdirunixmode(vol, upath, upriv) < 0 ) {
1956                     err = set_dir_errors(path, "setdirunixmode", errno);
1957                     goto setdirparam_done;
1958                 }
1959             }
1960             else {
1961                 err = AFPERR_BITMAP;
1962                 goto setdirparam_done;
1963             }
1964             break;
1965         default :
1966             err = AFPERR_BITMAP;
1967             goto setdirparam_done;
1968             break;
1969         }
1970
1971         bitmap = bitmap>>1;
1972         bit++;
1973     }
1974
1975 setdirparam_done:
1976     if (change_mdate && newdate == 0 && gettimeofday(&tv, NULL) == 0) {
1977         newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
1978     }
1979     if (newdate) {
1980         if (isad)
1981             ad_setdate(&ad, AD_DATE_MODIFY, newdate);
1982         ut.actime = ut.modtime = AD_DATE_TO_UNIX(newdate);
1983         utime(upath, &ut);
1984     }
1985
1986     if ( isad ) {
1987         if (path->st_valid && !path->st_errno) {
1988             struct stat *st = &path->st;
1989
1990             if (dir && dir->d_pdid) {
1991                 ad_setid(&ad, st->st_dev, st->st_ino,  dir->d_did, dir->d_pdid, vol->v_stamp);
1992             }
1993         }
1994         ad_flush( &ad);
1995         ad_close_metadata( &ad);
1996     }
1997
1998     if (change_parent_mdate && dir->d_did != DIRDID_ROOT
1999         && gettimeofday(&tv, NULL) == 0) {
2000         if (movecwd(vol, dirlookup(vol, dir->d_pdid)) == 0) {
2001             newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
2002             /* be careful with bitmap because now dir is null */
2003             bitmap = 1<<DIRPBIT_MDATE;
2004             setdirparams(vol, &Cur_Path, bitmap, (char *)&newdate);
2005             /* should we reset curdir ?*/
2006         }
2007     }
2008
2009     return err;
2010 }
2011
2012 int afp_syncdir(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2013 {
2014 #ifdef HAVE_DIRFD
2015     DIR                  *dp;
2016 #endif
2017     int                  dfd;
2018     struct vol           *vol;
2019     struct dir           *dir;
2020     u_int32_t            did;
2021     u_int16_t            vid;
2022
2023     *rbuflen = 0;
2024     ibuf += 2;
2025
2026     memcpy( &vid, ibuf, sizeof( vid ));
2027     ibuf += sizeof( vid );
2028     if (NULL == (vol = getvolbyvid( vid )) ) {
2029         return( AFPERR_PARAM );
2030     }
2031
2032     memcpy( &did, ibuf, sizeof( did ));
2033     ibuf += sizeof( did );
2034
2035     /*
2036      * Here's the deal:
2037      * if it's CNID 2 our only choice to meet the specs is call sync.
2038      * For any other CNID just sync that dir. To my knowledge the
2039      * intended use of FPSyncDir is to sync the volume so all we're
2040      * ever going to see here is probably CNID 2. Anyway, we' prepared.
2041      */
2042
2043     if ( ntohl(did) == 2 ) {
2044         sync();
2045     } else {
2046         if (NULL == ( dir = dirlookup( vol, did )) ) {
2047             return afp_errno; /* was AFPERR_NOOBJ */
2048         }
2049
2050         if (movecwd( vol, dir ) < 0 )
2051             return ( AFPERR_NOOBJ );
2052
2053         /*
2054          * Assuming only OSens that have dirfd also may require fsyncing directories
2055          * in order to flush metadata e.g. Linux.
2056          */
2057
2058 #ifdef HAVE_DIRFD
2059         if (NULL == ( dp = opendir( "." )) ) {
2060             switch( errno ) {
2061             case ENOENT :
2062                 return( AFPERR_NOOBJ );
2063             case EACCES :
2064                 return( AFPERR_ACCESS );
2065             default :
2066                 return( AFPERR_PARAM );
2067             }
2068         }
2069
2070         LOG(log_debug, logtype_afpd, "afp_syncdir: dir: '%s'", dir->d_u_name);
2071
2072         dfd = dirfd( dp );
2073         if ( fsync ( dfd ) < 0 )
2074             LOG(log_error, logtype_afpd, "afp_syncdir(%s):  %s",
2075                 dir->d_u_name, strerror(errno) );
2076         closedir(dp); /* closes dfd too */
2077 #endif
2078
2079         if ( -1 == (dfd = open(vol->ad_path(".", ADFLAGS_DIR), O_RDWR))) {
2080             switch( errno ) {
2081             case ENOENT:
2082                 return( AFPERR_NOOBJ );
2083             case EACCES:
2084                 return( AFPERR_ACCESS );
2085             default:
2086                 return( AFPERR_PARAM );
2087             }
2088         }
2089
2090         LOG(log_debug, logtype_afpd, "afp_syncdir: ad-file: '%s'",
2091             vol->ad_path(".", ADFLAGS_DIR) );
2092
2093         if ( fsync(dfd) < 0 )
2094             LOG(log_error, logtype_afpd, "afp_syncdir(%s): %s",
2095                 vol->ad_path(cfrombstr(dir->d_u_name), ADFLAGS_DIR), strerror(errno) );
2096         close(dfd);
2097     }
2098
2099     return ( AFP_OK );
2100 }
2101
2102 int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2103 {
2104     struct adouble  ad;
2105     struct vol      *vol;
2106     struct dir      *dir;
2107     char        *upath;
2108     struct path         *s_path;
2109     u_int32_t       did;
2110     u_int16_t       vid;
2111     int                 err;
2112
2113     *rbuflen = 0;
2114     ibuf += 2;
2115
2116     memcpy( &vid, ibuf, sizeof( vid ));
2117     ibuf += sizeof( vid );
2118     if (NULL == ( vol = getvolbyvid( vid )) ) {
2119         return( AFPERR_PARAM );
2120     }
2121
2122     if (vol->v_flags & AFPVOL_RO)
2123         return AFPERR_VLOCK;
2124
2125     memcpy( &did, ibuf, sizeof( did ));
2126     ibuf += sizeof( did );
2127     if (NULL == ( dir = dirlookup( vol, did )) ) {
2128         return afp_errno; /* was AFPERR_NOOBJ */
2129     }
2130     /* for concurrent access we need to be sure we are not in the
2131      * folder we want to create...
2132      */
2133     movecwd(vol, dir);
2134
2135     if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
2136         return get_afp_errno(AFPERR_PARAM);
2137     }
2138     /* cname was able to move curdir to it! */
2139     if (*s_path->m_name == '\0')
2140         return AFPERR_EXIST;
2141
2142     upath = s_path->u_name;
2143
2144     if (AFP_OK != (err = netatalk_mkdir(vol, upath))) {
2145         return err;
2146     }
2147
2148     if (of_stat(s_path) < 0) {
2149         return AFPERR_MISC;
2150     }
2151
2152     curdir->offcnt++;
2153
2154     if ((dir = dir_add(vol, curdir, s_path, strlen(s_path->u_name))) == NULL) {
2155         return AFPERR_MISC;
2156     }
2157
2158     if ( movecwd( vol, dir ) < 0 ) {
2159         return( AFPERR_PARAM );
2160     }
2161
2162     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2163     if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad ) < 0)  {
2164         if (vol_noadouble(vol))
2165             goto createdir_done;
2166         return( AFPERR_ACCESS );
2167     }
2168     ad_setname(&ad, s_path->m_name);
2169     ad_setid( &ad, s_path->st.st_dev, s_path->st.st_ino, dir->d_did, did, vol->v_stamp);
2170
2171     ad_flush( &ad);
2172     ad_close_metadata( &ad);
2173
2174 createdir_done:
2175     memcpy( rbuf, &dir->d_did, sizeof( u_int32_t ));
2176     *rbuflen = sizeof( u_int32_t );
2177     setvoltime(obj, vol );
2178     return( AFP_OK );
2179 }
2180
2181 /*
2182  * dst       new unix filename (not a pathname)
2183  * newname   new mac name
2184  * newparent curdir
2185  * dirfd     -1 means ignore dirfd (or use AT_FDCWD), otherwise src is relative to dirfd
2186  */
2187 int renamedir(const struct vol *vol,
2188               int dirfd,
2189               char *src,
2190               char *dst,
2191               struct dir *dir,
2192               struct dir *newparent,
2193               char *newname)
2194 {
2195     struct adouble  ad;
2196     int             err;
2197
2198     /* existence check moved to afp_moveandrename */
2199     if ( unix_rename(dirfd, src, -1, dst ) < 0 ) {
2200         switch ( errno ) {
2201         case ENOENT :
2202             return( AFPERR_NOOBJ );
2203         case EACCES :
2204             return( AFPERR_ACCESS );
2205         case EROFS:
2206             return AFPERR_VLOCK;
2207         case EINVAL:
2208             /* tried to move directory into a subdirectory of itself */
2209             return AFPERR_CANTMOVE;
2210         case EXDEV:
2211             /* this needs to copy and delete. bleah. that means we have
2212              * to deal with entire directory hierarchies. */
2213             if ((err = copydir(vol, dirfd, src, dst)) < 0) {
2214                 deletedir(-1, dst);
2215                 return err;
2216             }
2217             if ((err = deletedir(dirfd, src)) < 0)
2218                 return err;
2219             break;
2220         default :
2221             return( AFPERR_PARAM );
2222         }
2223     }
2224
2225     vol->vfs->vfs_renamedir(vol, dirfd, src, dst);
2226
2227     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2228
2229     if (!ad_open_metadata( dst, ADFLAGS_DIR, 0, &ad)) {
2230         ad_setname(&ad, newname);
2231         ad_flush( &ad);
2232         ad_close_metadata( &ad);
2233     }
2234
2235     return( AFP_OK );
2236 }
2237
2238 /* delete an empty directory */
2239 int deletecurdir(struct vol *vol)
2240 {
2241     struct dirent *de;
2242     struct stat st;
2243     struct dir  *fdir;
2244     DIR *dp;
2245     struct adouble  ad;
2246     u_int16_t       ashort;
2247     int err;
2248
2249     if ( dirlookup(vol, curdir->d_pdid) == NULL ) {
2250         return( AFPERR_ACCESS );
2251     }
2252
2253     fdir = curdir;
2254
2255     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2256     /* we never want to create a resource fork here, we are going to delete it */
2257     if ( ad_metadata( ".", ADFLAGS_DIR, &ad) == 0 ) {
2258
2259         ad_getattr(&ad, &ashort);
2260         ad_close_metadata(&ad);
2261         if ((ashort & htons(ATTRBIT_NODELETE))) {
2262             return  AFPERR_OLOCK;
2263         }
2264     }
2265     err = vol->vfs->vfs_deletecurdir(vol);
2266     if (err) {
2267         return err;
2268     }
2269
2270     /* now get rid of dangling symlinks */
2271     if ((dp = opendir("."))) {
2272         while ((de = readdir(dp))) {
2273             /* skip this and previous directory */
2274             if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
2275                 continue;
2276
2277             /* bail if it's not a symlink */
2278             if ((lstat(de->d_name, &st) == 0) && !S_ISLNK(st.st_mode)) {
2279                 closedir(dp);
2280                 return AFPERR_DIRNEMPT;
2281             }
2282
2283             if ((err = netatalk_unlink(de->d_name))) {
2284                 closedir(dp);
2285                 return err;
2286             }
2287         }
2288     }
2289
2290     if ( movecwd(vol, dirlookup(vol, curdir->d_pdid)) < 0 ) {
2291         err = afp_errno;
2292         goto delete_done;
2293     }
2294
2295     err = netatalk_rmdir_all_errors(-1, cfrombstr(fdir->d_u_name));
2296     if ( err ==  AFP_OK || err == AFPERR_NOOBJ) {
2297         cnid_delete(vol->v_cdb, fdir->d_did);
2298         dir_remove( vol, fdir );
2299     }
2300 delete_done:
2301     if (dp) {
2302         /* inode is used as key for cnid.
2303          * Close the descriptor only after cnid_delete
2304          * has been called.
2305          */
2306         closedir(dp);
2307     }
2308     return err;
2309 }
2310
2311 int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2312 {
2313     struct passwd   *pw;
2314     struct group    *gr;
2315     char        *name;
2316     u_int32_t           id;
2317     int         len, sfunc;
2318     int         utf8 = 0;
2319
2320     ibuf++;
2321     sfunc = (unsigned char) *ibuf++;
2322     *rbuflen = 0;
2323
2324     if (sfunc >= 3 && sfunc <= 6) {
2325         if (afp_version < 30) {
2326             return( AFPERR_PARAM );
2327         }
2328         utf8 = 1;
2329     }
2330
2331     switch ( sfunc ) {
2332     case 1 :
2333     case 3 :/* unicode */
2334         memcpy( &id, ibuf, sizeof( id ));
2335         id = ntohl(id);
2336         if ( id != 0 ) {
2337             if (( pw = getpwuid( id )) == NULL ) {
2338                 return( AFPERR_NOITEM );
2339             }
2340             len = convert_string_allocate( obj->options.unixcharset, ((!utf8)?obj->options.maccharset:CH_UTF8_MAC),
2341                                            pw->pw_name, -1, &name);
2342         } else {
2343             len = 0;
2344             name = NULL;
2345         }
2346         break;
2347     case 2 :
2348     case 4 : /* unicode */
2349         memcpy( &id, ibuf, sizeof( id ));
2350         id = ntohl(id);
2351         if ( id != 0 ) {
2352             if (NULL == ( gr = (struct group *)getgrgid( id ))) {
2353                 return( AFPERR_NOITEM );
2354             }
2355             len = convert_string_allocate( obj->options.unixcharset, (!utf8)?obj->options.maccharset:CH_UTF8_MAC,
2356                                            gr->gr_name, -1, &name);
2357         } else {
2358             len = 0;
2359             name = NULL;
2360         }
2361         break;
2362
2363     case 5 : /* UUID -> username */
2364     case 6 : /* UUID -> groupname */
2365         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2366             return AFPERR_PARAM;
2367         LOG(log_debug, logtype_afpd, "afp_mapid: valid UUID request");
2368         uuidtype_t type;
2369         len = getnamefromuuid((unsigned char*) ibuf, &name, &type);
2370         if (len != 0)       /* its a error code, not len */
2371             return AFPERR_NOITEM;
2372         switch (type) {
2373         case UUID_USER:
2374             if (( pw = getpwnam( name )) == NULL )
2375                 return( AFPERR_NOITEM );
2376             LOG(log_debug, logtype_afpd, "afp_mapid: name:%s -> uid:%d", name, pw->pw_uid);
2377             id = htonl(UUID_USER);
2378             memcpy( rbuf, &id, sizeof( id ));
2379             id = htonl( pw->pw_uid);
2380             rbuf += sizeof( id );
2381             memcpy( rbuf, &id, sizeof( id ));
2382             rbuf += sizeof( id );
2383             *rbuflen = 2 * sizeof( id );
2384             break;
2385         case UUID_GROUP:
2386             if (( gr = getgrnam( name )) == NULL )
2387                 return( AFPERR_NOITEM );
2388             LOG(log_debug, logtype_afpd, "afp_mapid: group:%s -> gid:%d", name, gr->gr_gid);
2389             id = htonl(UUID_GROUP);
2390             memcpy( rbuf, &id, sizeof( id ));
2391             rbuf += sizeof( id );
2392             id = htonl( gr->gr_gid);
2393             memcpy( rbuf, &id, sizeof( id ));
2394             rbuf += sizeof( id );
2395             *rbuflen = 2 * sizeof( id );
2396             break;
2397         case UUID_LOCAL:
2398             free(name);
2399             return (AFPERR_NOITEM);
2400         default:
2401             return AFPERR_MISC;
2402         }
2403         break;
2404
2405     default :
2406         return( AFPERR_PARAM );
2407     }
2408
2409     if (name)
2410         len = strlen( name );
2411
2412     if (utf8) {
2413         u_int16_t tp = htons(len);
2414         memcpy(rbuf, &tp, sizeof(tp));
2415         rbuf += sizeof(tp);
2416         *rbuflen += 2;
2417     }
2418     else {
2419         *rbuf++ = len;
2420         *rbuflen += 1;
2421     }
2422     if ( len > 0 ) {
2423         memcpy( rbuf, name, len );
2424     }
2425     *rbuflen += len;
2426     if (name)
2427         free(name);
2428     return( AFP_OK );
2429 }
2430
2431 int afp_mapname(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2432 {
2433     struct passwd   *pw;
2434     struct group    *gr;
2435     int             len, sfunc;
2436     u_int32_t       id;
2437     u_int16_t       ulen;
2438
2439     ibuf++;
2440     sfunc = (unsigned char) *ibuf++;
2441     *rbuflen = 0;
2442     LOG(log_debug, logtype_afpd, "afp_mapname: sfunc: %d, afp_version: %d", sfunc, afp_version);
2443     switch ( sfunc ) {
2444     case 1 :
2445     case 2 : /* unicode */
2446         if (afp_version < 30) {
2447             return( AFPERR_PARAM );
2448         }
2449         memcpy(&ulen, ibuf, sizeof(ulen));
2450         len = ntohs(ulen);
2451         ibuf += 2;
2452         LOG(log_debug, logtype_afpd, "afp_mapname: alive");
2453         break;
2454     case 3 :
2455     case 4 :
2456         len = (unsigned char) *ibuf++;
2457         break;
2458     case 5 : /* username -> UUID  */
2459     case 6 : /* groupname -> UUID */
2460         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2461             return AFPERR_PARAM;
2462         memcpy(&ulen, ibuf, sizeof(ulen));
2463         len = ntohs(ulen);
2464         ibuf += 2;
2465         break;
2466     default :
2467         return( AFPERR_PARAM );
2468     }
2469
2470     ibuf[ len ] = '\0';
2471
2472     if ( len == 0 )
2473         return AFPERR_PARAM;
2474     else {
2475         switch ( sfunc ) {
2476         case 1 : /* unicode */
2477         case 3 :
2478             if (NULL == ( pw = (struct passwd *)getpwnam( ibuf )) ) {
2479                 return( AFPERR_NOITEM );
2480             }
2481             id = pw->pw_uid;
2482             id = htonl(id);
2483             memcpy( rbuf, &id, sizeof( id ));
2484             *rbuflen = sizeof( id );
2485             break;
2486
2487         case 2 : /* unicode */
2488         case 4 :
2489             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s",ibuf);
2490             if (NULL == ( gr = (struct group *)getgrnam( ibuf ))) {
2491                 return( AFPERR_NOITEM );
2492             }
2493             id = gr->gr_gid;
2494             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s -> id: %d",ibuf, id);
2495             id = htonl(id);
2496             memcpy( rbuf, &id, sizeof( id ));
2497             *rbuflen = sizeof( id );
2498             break;
2499         case 5 :        /* username -> UUID */
2500             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2501             if (0 != getuuidfromname(ibuf, UUID_USER, (unsigned char *)rbuf))
2502                 return AFPERR_NOITEM;
2503             *rbuflen = UUID_BINSIZE;
2504             break;
2505         case 6 :        /* groupname -> UUID */
2506             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2507             if (0 != getuuidfromname(ibuf, UUID_GROUP, (unsigned char *)rbuf))
2508                 return AFPERR_NOITEM;
2509             *rbuflen = UUID_BINSIZE;
2510             break;
2511         }
2512     }
2513     return( AFP_OK );
2514 }
2515
2516 /* ------------------------------------
2517    variable DID support
2518 */
2519 int afp_closedir(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2520 {
2521 #if 0
2522     struct vol   *vol;
2523     struct dir   *dir;
2524     u_int16_t    vid;
2525     u_int32_t    did;
2526 #endif /* 0 */
2527
2528     *rbuflen = 0;
2529
2530     /* do nothing as dids are static for the life of the process. */
2531 #if 0
2532     ibuf += 2;
2533
2534     memcpy(&vid,  ibuf, sizeof( vid ));
2535     ibuf += sizeof( vid );
2536     if (( vol = getvolbyvid( vid )) == NULL ) {
2537         return( AFPERR_PARAM );
2538     }
2539
2540     memcpy( &did, ibuf, sizeof( did ));
2541     ibuf += sizeof( did );
2542     if (( dir = dirlookup( vol, did )) == NULL ) {
2543         return( AFPERR_PARAM );
2544     }
2545
2546     /* dir_remove -- deletedid */
2547 #endif /* 0 */
2548
2549     return AFP_OK;
2550 }
2551
2552 /* did creation gets done automatically
2553  * there's a pb again with case but move it to cname
2554  */
2555 int afp_opendir(AFPObj *obj _U_, char *ibuf, size_t ibuflen  _U_, char *rbuf, size_t *rbuflen)
2556 {
2557     struct vol      *vol;
2558     struct dir      *parentdir;
2559     struct path     *path;
2560     u_int32_t       did;
2561     u_int16_t       vid;
2562
2563     *rbuflen = 0;
2564     ibuf += 2;
2565
2566     memcpy(&vid, ibuf, sizeof(vid));
2567     ibuf += sizeof( vid );
2568
2569     if (NULL == ( vol = getvolbyvid( vid )) ) {
2570         return( AFPERR_PARAM );
2571     }
2572
2573     memcpy(&did, ibuf, sizeof(did));
2574     ibuf += sizeof(did);
2575
2576     if (NULL == ( parentdir = dirlookup( vol, did )) ) {
2577         return afp_errno;
2578     }
2579
2580     if (NULL == ( path = cname( vol, parentdir, &ibuf )) ) {
2581         return get_afp_errno(AFPERR_PARAM);
2582     }
2583
2584     if ( *path->m_name != '\0' ) {
2585         return path_error(path, AFPERR_NOOBJ);
2586     }
2587
2588     if ( !path->st_valid && of_stat(path ) < 0 ) {
2589         return( AFPERR_NOOBJ );
2590     }
2591     if ( path->st_errno ) {
2592         return( AFPERR_NOOBJ );
2593     }
2594
2595     memcpy(rbuf, &curdir->d_did, sizeof(curdir->d_did));
2596     *rbuflen = sizeof(curdir->d_did);
2597     return AFP_OK;
2598 }