]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/directory.c
Protect dircache from duplicates
[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(vol, 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(vol, 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 #if 0 /* unused */
921 /*!
922  * @brief Modify a struct dir, adjust cache
923  *
924  * Any value that is 0 or NULL is not changed. If new_uname is NULL it is set to new_mname.
925  * If given new_uname == new_mname, new_uname will point to new_mname.
926  *
927  * @param vol       (r) pointer to struct vol
928  * @param dir       (rw) pointer to struct dir
929  * @param pdid      (r) new parent DID
930  * @param did       (r) new DID
931  * @param new_mname (r) new mac-name
932  * @param new_uname (r) new unix-name
933  * @param pdir_fullpath (r) new fullpath of parent dir
934  */
935 int dir_modify(const struct vol *vol,
936                struct dir *dir,
937                cnid_t pdid,
938                cnid_t did,
939                const char *new_mname,
940                const char *new_uname,
941                bstring pdir_fullpath)
942 {
943     int ret = 0;
944
945     /* Remove it from the cache */
946     dircache_remove(vol, dir, DIRCACHE | DIDNAME_INDEX | QUEUE_INDEX);
947
948     if (pdid)
949         dir->d_pdid = pdid;
950     if (did)
951         dir->d_did = did;
952
953     if (new_mname) {
954         /* free uname if it's not the same as mname */
955         if (dir->d_m_name != dir->d_u_name)
956             bdestroy(dir->d_u_name);
957
958         if (new_uname == NULL)
959             new_uname = new_mname;
960
961         /* assign new name */
962         if ((bassigncstr(dir->d_m_name, new_mname)) != BSTR_OK) {
963             LOG(log_error, logtype_afpd, "dir_modify: bassigncstr: %s", strerror(errno) );
964             return -1;
965         }
966
967         if (new_mname == new_uname || (strcmp(new_mname, new_uname) == 0)) {
968             dir->d_u_name = dir->d_m_name;
969         } else {
970             if ((dir->d_u_name = bfromcstr(new_uname)) == NULL) {
971                 LOG(log_error, logtype_afpd, "dir_modify: bassigncstr: %s", strerror(errno) );
972                 return -1;
973             }
974         }
975     }
976
977     if (pdir_fullpath) {
978         if (bassign(dir->d_fullpath, pdir_fullpath) != BSTR_OK)
979             return -1;
980         if (bcatcstr(dir->d_fullpath, "/") != BSTR_OK)
981             return -1;
982         if (bcatcstr(dir->d_fullpath, new_uname) != BSTR_OK)
983             return -1;
984     }
985
986     if (dir->d_m_name_ucs2)
987         free(dir->d_m_name_ucs2);
988     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))
989         dir->d_m_name_ucs2 = NULL;
990
991     /* Re-add it to the cache */
992     if ((dircache_add(vol, dir)) != 0) {
993         dircache_dump();
994         AFP_PANIC("dir_modify");
995     }
996
997     return ret;
998 }
999 #endif
1000
1001 /*!
1002  * @brief Resolve a catalog node name path
1003  *
1004  * 1. Evaluate path type
1005  * 2. Move to start dir, if we cant, it might eg because of EACCES, build
1006  *    path from dirname, so eg getdirparams has sth it can chew on. curdir
1007  *    is dir parent then. All this is done in path_from_dir().
1008  * 3. Parse next cnode name in path, cases:
1009  * 4.   single "\0" -> do nothing
1010  * 5.   two or more consecutive "\0" -> chdir("..") one or more times
1011  * 6.   cnode name -> copy it to path.m_name
1012  * 7. Get unix name from mac name
1013  * 8. Special handling of request with did 1
1014  * 9. stat the cnode name
1015  * 10. If it's not there, it's probably an afp_createfile|dir,
1016  *     return with curdir = dir parent, struct path = dirname
1017  * 11. If it's there and it's a file, it must should be the last element of the requested
1018  *     path. Return with curdir = cnode name parent dir, struct path = filename
1019  * 12. Treat symlinks like files, dont follow them
1020  * 13. If it's a dir:
1021  * 14. Search the dircache for it
1022  * 15. If it's not in the cache, create a struct dir for it and add it to the cache
1023  * 16. chdir into the dir and
1024  * 17. set m_name to the mac equivalent of "."
1025  * 18. goto 3
1026  */
1027 struct path *cname(struct vol *vol, struct dir *dir, char **cpath)
1028 {
1029     static char        path[ MAXPATHLEN + 1];
1030     static struct path ret;
1031
1032     struct dir  *cdir;
1033     char        *data, *p;
1034     int         len;
1035     u_int32_t   hint;
1036     u_int16_t   len16;
1037     int         size = 0;
1038     int         toUTF8 = 0;
1039
1040     LOG(log_maxdebug, logtype_afpd, "came('%s'): {start}", cfrombstr(dir->d_fullpath));
1041
1042     data = *cpath;
1043     afp_errno = AFPERR_NOOBJ;
1044     memset(&ret, 0, sizeof(ret));
1045
1046     switch (ret.m_type = *data) { /* 1 */
1047     case 2:
1048         data++;
1049         len = (unsigned char) *data++;
1050         size = 2;
1051         if (afp_version >= 30) {
1052             ret.m_type = 3;
1053             toUTF8 = 1;
1054         }
1055         break;
1056     case 3:
1057         if (afp_version >= 30) {
1058             data++;
1059             memcpy(&hint, data, sizeof(hint));
1060             hint = ntohl(hint);
1061             data += sizeof(hint);
1062
1063             memcpy(&len16, data, sizeof(len16));
1064             len = ntohs(len16);
1065             data += 2;
1066             size = 7;
1067             break;
1068         }
1069         /* else it's an error */
1070     default:
1071         afp_errno = AFPERR_PARAM;
1072         return( NULL );
1073     }
1074     *cpath += len + size;
1075
1076     path[0] = 0;
1077     ret.m_name = path;
1078
1079     if (movecwd(vol, dir) < 0 ) {
1080         LOG(log_debug, logtype_afpd, "cname(did:%u): failed to chdir to '%s'",
1081             ntohl(dir->d_did), cfrombstr(dir->d_fullpath));
1082         if (len == 0)
1083             return path_from_dir(vol, dir, &ret);
1084         else
1085             return NULL;
1086     }
1087
1088     while (len) {         /* 3 */
1089         if (*data == 0) { /* 4 or 5 */
1090             data++;
1091             len--;
1092             while (len > 0 && *data == 0) { /* 5 */
1093                 /* chdir to parrent dir */
1094                 if ((dir = dirlookup(vol, dir->d_pdid)) == NULL)
1095                     return NULL;
1096                 if (movecwd( vol, dir ) < 0 ) {
1097                     dir_remove(vol, dir);
1098                     return NULL;
1099                 }
1100                 data++;
1101                 len--;
1102             }
1103             continue;
1104         }
1105
1106         /* 6*/
1107         for ( p = path; *data != 0 && len > 0; len-- ) {
1108             *p++ = *data++;
1109             if (p > &path[UTF8FILELEN_EARLY]) {   /* FIXME safeguard, limit of early Mac OS X */
1110                 afp_errno = AFPERR_PARAM;
1111                 return NULL;
1112             }
1113         }
1114         *p = 0;            /* Terminate string */
1115         ret.u_name = NULL;
1116
1117         if (cname_mtouname(vol, dir, &ret, toUTF8) != 0) { /* 7 */
1118             LOG(log_error, logtype_afpd, "cname('%s'): error from cname_mtouname", path);
1119             return NULL;
1120         }
1121
1122         LOG(log_maxdebug, logtype_afpd, "came('%s'): {node: '%s}", cfrombstr(dir->d_fullpath), ret.u_name);
1123
1124         /* Prevent access to our special folders like .AppleDouble */
1125         if (check_name(vol, ret.u_name)) {
1126             /* the name is illegal */
1127             LOG(log_info, logtype_afpd, "cname: illegal path: '%s'", ret.u_name);
1128             afp_errno = AFPERR_PARAM;
1129             return NULL;
1130         }
1131
1132         if (dir->d_did == DIRDID_ROOT_PARENT) { /* 8 */
1133             /*
1134              * Special case: CNID 1
1135              * root parent (did 1) has one child: the volume. Requests for did=1 with
1136              * some <name> must check against the volume name.
1137              */
1138             if ((strcmp(cfrombstr(vol->v_root->d_m_name), ret.m_name)) == 0)
1139                 cdir = vol->v_root;
1140             else
1141                 return NULL;
1142         } else {
1143             /*
1144              * CNID != 1, eg. most of the times we take this way.
1145              * Now check if current path-part is a file or dir:
1146              * o if it's dir we have to step into it
1147              * o if it's a file we expect it to be the last part of the requested path
1148              *   and thus call continue which should terminate the while loop because
1149              *   len = 0. Ok?
1150              */
1151             if (of_stat(&ret) != 0) { /* 9 */
1152                 /*
1153                  * ret.u_name doesn't exist, might be afp_createfile|dir
1154                  * that means it should have been the last part
1155                  */
1156                 if (len > 0) {
1157                     /* it wasn't the last part, so we have a bogus path request */
1158                     afp_errno = AFPERR_NOOBJ;
1159                     return NULL;
1160                 }
1161                 /*
1162                  * this will terminate clean in while (1) because len == 0,
1163                  * probably afp_createfile|dir
1164                  */
1165                 LOG(log_maxdebug, logtype_afpd, "came('%s'): {leave-cnode ENOENT (possile create request): '%s'}",
1166                     cfrombstr(dir->d_fullpath), ret.u_name);
1167                 continue; /* 10 */
1168             }
1169
1170             switch (ret.st.st_mode & S_IFMT) {
1171             case S_IFREG: /* 11 */
1172                 LOG(log_debug, logtype_afpd, "came('%s'): {file: '%s'}",
1173                     cfrombstr(dir->d_fullpath), ret.u_name);
1174                 if (len > 0) {
1175                     /* it wasn't the last part, so we have a bogus path request */
1176                     afp_errno = AFPERR_PARAM;
1177                     return NULL;
1178                 }
1179                 continue; /* continues while loop */
1180             case S_IFLNK: /* 12 */
1181                 LOG(log_debug, logtype_afpd, "came('%s'): {link: '%s'}",
1182                     cfrombstr(dir->d_fullpath), ret.u_name);
1183                 if (len > 0) {
1184                     LOG(log_warning, logtype_afpd, "came('%s'): {symlinked dir: '%s'}",
1185                         cfrombstr(dir->d_fullpath), ret.u_name);
1186                     afp_errno = AFPERR_PARAM;
1187                     return NULL;
1188                 }
1189                 continue; /* continues while loop */
1190             case S_IFDIR: /* 13 */
1191                 break;
1192             default:
1193                 LOG(log_info, logtype_afpd, "cname: special file: '%s'", ret.u_name);
1194                 afp_errno = AFPERR_NODIR;
1195                 return NULL;
1196             }
1197
1198             /* Search the cache */
1199             int unamelen = strlen(ret.u_name);
1200             cdir = dircache_search_by_name(vol, dir, ret.u_name, unamelen, ret.st.st_ctime); /* 14 */
1201             if (cdir == NULL) {
1202                 /* Not in cache, create one */
1203                 if ((cdir = dir_add(vol, dir, &ret, unamelen)) == NULL) { /* 15 */
1204                     LOG(log_error, logtype_afpd, "cname(did:%u, name:'%s', cwd:'%s'): failed to add dir",
1205                         ntohl(dir->d_did), ret.u_name, getcwdpath());
1206                     return NULL;
1207                 }
1208             }
1209         } /* if/else cnid==1 */
1210
1211         /* Now chdir to the evaluated dir */
1212         if (movecwd( vol, cdir ) < 0 ) { /* 16 */
1213             LOG(log_debug, logtype_afpd, "cname(cwd:'%s'): failed to chdir to new subdir '%s': %s",
1214                 cfrombstr(curdir->d_fullpath), cfrombstr(cdir->d_fullpath), strerror(errno));
1215             if (len == 0)
1216                 return path_from_dir(vol, cdir, &ret);
1217             else
1218                 return NULL;
1219         }
1220         dir = cdir;
1221         ret.m_name[0] = 0;      /* 17, so we later know last token was a dir */
1222     } /* while (len) */
1223
1224     if (curdir->d_did == DIRDID_ROOT_PARENT) {
1225         afp_errno = AFPERR_DID1;
1226         return NULL;
1227     }
1228
1229     if (ret.m_name[0] == 0) {
1230         /* Last part was a dir */
1231         ret.u_name = mtoupath(vol, ret.m_name, 0, 1); /* Force "." into a useable static buffer */
1232         ret.d_dir = dir;
1233     }
1234
1235     LOG(log_debug, logtype_afpd, "came('%s') {end: curdir:'%s', path:'%s'}",
1236         cfrombstr(dir->d_fullpath),
1237         cfrombstr(curdir->d_fullpath),
1238         ret.u_name);
1239
1240     return &ret;
1241 }
1242
1243 /*
1244  * @brief chdir() to dir
1245  *
1246  * @param vol   (r) pointer to struct vol
1247  * @param dir   (r) pointer to struct dir
1248  *
1249  * @returns 0 on success, -1 on error with afp_errno set appropiately
1250  */
1251 int movecwd(const struct vol *vol, struct dir *dir)
1252 {
1253     int ret;
1254
1255     AFP_ASSERT(vol);
1256     AFP_ASSERT(dir);
1257
1258     LOG(log_maxdebug, logtype_afpd, "movecwd(curdir:'%s', cwd:'%s')",
1259         cfrombstr(curdir->d_fullpath), getcwdpath());
1260
1261     if ( dir == curdir)
1262         return( 0 );
1263     if (dir->d_did == DIRDID_ROOT_PARENT) {
1264         curdir = &rootParent;
1265         return 0;
1266     }
1267
1268     LOG(log_debug, logtype_afpd, "movecwd(did:%u, '%s')",
1269         ntohl(dir->d_did), cfrombstr(dir->d_fullpath));
1270
1271     if ((ret = lchdir(cfrombstr(dir->d_fullpath))) != 0 ) {
1272         LOG(log_debug, logtype_afpd, "movecwd('%s'): ret: %u, %s",
1273             cfrombstr(dir->d_fullpath), ret, strerror(errno));
1274         if (ret == 1) {
1275             /* p is a symlink or getcwd failed */
1276             afp_errno = AFPERR_BADTYPE;
1277
1278             if (chdir(vol->v_path ) < 0) {
1279                 LOG(log_error, logtype_afpd, "can't chdir back'%s': %s", vol->v_path, strerror(errno));
1280                 /* XXX what do we do here? */
1281             }
1282             curdir = vol->v_root;
1283             return -1;
1284         }
1285
1286         switch (errno) {
1287         case EACCES:
1288         case EPERM:
1289             afp_errno = AFPERR_ACCESS;
1290             break;
1291         default:
1292             afp_errno = AFPERR_NOOBJ;
1293         }
1294         return( -1 );
1295     }
1296
1297     curdir = dir;
1298     return( 0 );
1299 }
1300
1301 /*
1302  * We can't use unix file's perm to support Apple's inherited protection modes.
1303  * If we aren't the file's owner we can't change its perms when moving it and smb
1304  * nfs,... don't even try.
1305  */
1306 #define AFP_CHECK_ACCESS
1307
1308 int check_access(char *path, int mode)
1309 {
1310 #ifdef AFP_CHECK_ACCESS
1311     struct maccess ma;
1312     char *p;
1313
1314     p = ad_dir(path);
1315     if (!p)
1316         return -1;
1317
1318     accessmode(p, &ma, curdir, NULL);
1319     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE))
1320         return -1;
1321     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD))
1322         return -1;
1323 #endif
1324     return 0;
1325 }
1326
1327 /* --------------------- */
1328 int file_access(struct path *path, int mode)
1329 {
1330     struct maccess ma;
1331
1332     accessmode(path->u_name, &ma, curdir, &path->st);
1333
1334     LOG(log_debug, logtype_afpd, "file_access(\"%s\"): mapped user mode: 0x%02x",
1335         path->u_name, ma.ma_user);
1336
1337     if ((mode & OPENACC_WR) && !(ma.ma_user & AR_UWRITE)) {
1338         LOG(log_debug, logtype_afpd, "file_access(\"%s\"): write access denied", path->u_name);
1339         return -1;
1340     }
1341     if ((mode & OPENACC_RD) && !(ma.ma_user & AR_UREAD)) {
1342         LOG(log_debug, logtype_afpd, "file_access(\"%s\"): read access denied", path->u_name);
1343         return -1;
1344     }
1345     return 0;
1346
1347 }
1348
1349 /* --------------------- */
1350 void setdiroffcnt(struct dir *dir, struct stat *st,  u_int32_t count)
1351 {
1352     dir->offcnt = count;
1353     dir->ctime = st->st_ctime;
1354     dir->d_flags &= ~DIRF_CNID;
1355 }
1356
1357
1358 /* ---------------------
1359  * is our cached also for reenumerate id?
1360  */
1361 int dirreenumerate(struct dir *dir, struct stat *st)
1362 {
1363     return st->st_ctime == dir->ctime && (dir->d_flags & DIRF_CNID);
1364 }
1365
1366 /* ------------------------------
1367    (".", curdir)
1368    (name, dir) with curdir:name == dir, from afp_enumerate
1369 */
1370
1371 int getdirparams(const struct vol *vol,
1372                  u_int16_t bitmap, struct path *s_path,
1373                  struct dir *dir,
1374                  char *buf, size_t *buflen )
1375 {
1376     struct maccess  ma;
1377     struct adouble  ad;
1378     char        *data, *l_nameoff = NULL, *utf_nameoff = NULL;
1379     int         bit = 0, isad = 0;
1380     u_int32_t           aint;
1381     u_int16_t       ashort;
1382     int                 ret;
1383     u_int32_t           utf8 = 0;
1384     cnid_t              pdid;
1385     struct stat *st = &s_path->st;
1386     char *upath = s_path->u_name;
1387
1388     if ((bitmap & ((1 << DIRPBIT_ATTR)  |
1389                    (1 << DIRPBIT_CDATE) |
1390                    (1 << DIRPBIT_MDATE) |
1391                    (1 << DIRPBIT_BDATE) |
1392                    (1 << DIRPBIT_FINFO)))) {
1393
1394         ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1395         if ( !ad_metadata( upath, ADFLAGS_CREATE|ADFLAGS_DIR, &ad) ) {
1396             isad = 1;
1397             if (ad.ad_md->adf_flags & O_CREAT) {
1398                 /* We just created it */
1399                 ad_setname(&ad, s_path->m_name);
1400                 ad_setid( &ad,
1401                           s_path->st.st_dev,
1402                           s_path->st.st_ino,
1403                           dir->d_did,
1404                           dir->d_pdid,
1405                           vol->v_stamp);
1406                 ad_flush( &ad);
1407             }
1408         }
1409     }
1410
1411     pdid = dir->d_pdid;
1412
1413     data = buf;
1414     while ( bitmap != 0 ) {
1415         while (( bitmap & 1 ) == 0 ) {
1416             bitmap = bitmap>>1;
1417             bit++;
1418         }
1419
1420         switch ( bit ) {
1421         case DIRPBIT_ATTR :
1422             if ( isad ) {
1423                 ad_getattr(&ad, &ashort);
1424             } else if (invisible_dots(vol, cfrombstr(dir->d_u_name))) {
1425                 ashort = htons(ATTRBIT_INVISIBLE);
1426             } else
1427                 ashort = 0;
1428             ashort |= htons(ATTRBIT_SHARED);
1429             memcpy( data, &ashort, sizeof( ashort ));
1430             data += sizeof( ashort );
1431             break;
1432
1433         case DIRPBIT_PDID :
1434             memcpy( data, &pdid, sizeof( pdid ));
1435             data += sizeof( pdid );
1436             LOG(log_debug, logtype_afpd, "metadata('%s'):     Parent DID: %u",
1437                 s_path->u_name, ntohl(pdid));
1438             break;
1439
1440         case DIRPBIT_CDATE :
1441             if (!isad || (ad_getdate(&ad, AD_DATE_CREATE, &aint) < 0))
1442                 aint = AD_DATE_FROM_UNIX(st->st_mtime);
1443             memcpy( data, &aint, sizeof( aint ));
1444             data += sizeof( aint );
1445             break;
1446
1447         case DIRPBIT_MDATE :
1448             aint = AD_DATE_FROM_UNIX(st->st_mtime);
1449             memcpy( data, &aint, sizeof( aint ));
1450             data += sizeof( aint );
1451             break;
1452
1453         case DIRPBIT_BDATE :
1454             if (!isad || (ad_getdate(&ad, AD_DATE_BACKUP, &aint) < 0))
1455                 aint = AD_DATE_START;
1456             memcpy( data, &aint, sizeof( aint ));
1457             data += sizeof( aint );
1458             break;
1459
1460         case DIRPBIT_FINFO :
1461             if ( isad ) {
1462                 memcpy( data, ad_entry( &ad, ADEID_FINDERI ), 32 );
1463             } else { /* no appledouble */
1464                 memset( data, 0, 32 );
1465                 /* set default view -- this also gets done in ad_open() */
1466                 ashort = htons(FINDERINFO_CLOSEDVIEW);
1467                 memcpy(data + FINDERINFO_FRVIEWOFF, &ashort, sizeof(ashort));
1468
1469                 /* dot files are by default visible */
1470                 if (invisible_dots(vol, cfrombstr(dir->d_u_name))) {
1471                     ashort = htons(FINDERINFO_INVISIBLE);
1472                     memcpy(data + FINDERINFO_FRFLAGOFF, &ashort, sizeof(ashort));
1473                 }
1474             }
1475             data += 32;
1476             break;
1477
1478         case DIRPBIT_LNAME :
1479             if (dir->d_m_name) /* root of parent can have a null name */
1480                 l_nameoff = data;
1481             else
1482                 memset(data, 0, sizeof(u_int16_t));
1483             data += sizeof( u_int16_t );
1484             break;
1485
1486         case DIRPBIT_SNAME :
1487             memset(data, 0, sizeof(u_int16_t));
1488             data += sizeof( u_int16_t );
1489             break;
1490
1491         case DIRPBIT_DID :
1492             memcpy( data, &dir->d_did, sizeof( aint ));
1493             data += sizeof( aint );
1494             LOG(log_debug, logtype_afpd, "metadata('%s'):            DID: %u",
1495                 s_path->u_name, ntohl(dir->d_did));
1496             break;
1497
1498         case DIRPBIT_OFFCNT :
1499             ashort = 0;
1500             /* this needs to handle current directory access rights */
1501             if (diroffcnt(dir, st)) {
1502                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1503             }
1504             else if ((ret = for_each_dirent(vol, upath, NULL,NULL)) >= 0) {
1505                 setdiroffcnt(dir, st,  ret);
1506                 ashort = (dir->offcnt > 0xffff)?0xffff:dir->offcnt;
1507             }
1508             ashort = htons( ashort );
1509             memcpy( data, &ashort, sizeof( ashort ));
1510             data += sizeof( ashort );
1511             break;
1512
1513         case DIRPBIT_UID :
1514             aint = htonl(st->st_uid);
1515             memcpy( data, &aint, sizeof( aint ));
1516             data += sizeof( aint );
1517             break;
1518
1519         case DIRPBIT_GID :
1520             aint = htonl(st->st_gid);
1521             memcpy( data, &aint, sizeof( aint ));
1522             data += sizeof( aint );
1523             break;
1524
1525         case DIRPBIT_ACCESS :
1526             accessmode( upath, &ma, dir , st);
1527
1528             *data++ = ma.ma_user;
1529             *data++ = ma.ma_world;
1530             *data++ = ma.ma_group;
1531             *data++ = ma.ma_owner;
1532             break;
1533
1534             /* Client has requested the ProDOS information block.
1535                Just pass back the same basic block for all
1536                directories. <shirsch@ibm.net> */
1537         case DIRPBIT_PDINFO :
1538             if (afp_version >= 30) { /* UTF8 name */
1539                 utf8 = kTextEncodingUTF8;
1540                 if (dir->d_m_name) /* root of parent can have a null name */
1541                     utf_nameoff = data;
1542                 else
1543                     memset(data, 0, sizeof(u_int16_t));
1544                 data += sizeof( u_int16_t );
1545                 aint = 0;
1546                 memcpy(data, &aint, sizeof( aint ));
1547                 data += sizeof( aint );
1548             }
1549             else { /* ProDOS Info Block */
1550                 *data++ = 0x0f;
1551                 *data++ = 0;
1552                 ashort = htons( 0x0200 );
1553                 memcpy( data, &ashort, sizeof( ashort ));
1554                 data += sizeof( ashort );
1555                 memset( data, 0, sizeof( ashort ));
1556                 data += sizeof( ashort );
1557             }
1558             break;
1559
1560         case DIRPBIT_UNIXPR :
1561             aint = htonl(st->st_uid);
1562             memcpy( data, &aint, sizeof( aint ));
1563             data += sizeof( aint );
1564             aint = htonl(st->st_gid);
1565             memcpy( data, &aint, sizeof( aint ));
1566             data += sizeof( aint );
1567
1568             aint = st->st_mode;
1569             aint = htonl ( aint & ~S_ISGID );  /* Remove SGID, OSX doesn't like it ... */
1570             memcpy( data, &aint, sizeof( aint ));
1571             data += sizeof( aint );
1572
1573             accessmode( upath, &ma, dir , st);
1574
1575             *data++ = ma.ma_user;
1576             *data++ = ma.ma_world;
1577             *data++ = ma.ma_group;
1578             *data++ = ma.ma_owner;
1579             break;
1580
1581         default :
1582             if ( isad ) {
1583                 ad_close_metadata( &ad );
1584             }
1585             return( AFPERR_BITMAP );
1586         }
1587         bitmap = bitmap>>1;
1588         bit++;
1589     }
1590     if ( l_nameoff ) {
1591         ashort = htons( data - buf );
1592         memcpy( l_nameoff, &ashort, sizeof( ashort ));
1593         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, 0);
1594     }
1595     if ( utf_nameoff ) {
1596         ashort = htons( data - buf );
1597         memcpy( utf_nameoff, &ashort, sizeof( ashort ));
1598         data = set_name(vol, data, pdid, cfrombstr(dir->d_m_name), dir->d_did, utf8);
1599     }
1600     if ( isad ) {
1601         ad_close_metadata( &ad );
1602     }
1603     *buflen = data - buf;
1604     return( AFP_OK );
1605 }
1606
1607 /* ----------------------------- */
1608 int path_error(struct path *path, int error)
1609 {
1610 /* - a dir with access error
1611  * - no error it's a file
1612  * - file not found
1613  */
1614     if (path_isadir(path))
1615         return afp_errno;
1616     if (path->st_valid && path->st_errno)
1617         return error;
1618     return AFPERR_BADTYPE ;
1619 }
1620
1621 /* ----------------------------- */
1622 int afp_setdirparams(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
1623 {
1624     struct vol  *vol;
1625     struct dir  *dir;
1626     struct path *path;
1627     u_int16_t   vid, bitmap;
1628     u_int32_t   did;
1629     int     rc;
1630
1631     *rbuflen = 0;
1632     ibuf += 2;
1633     memcpy( &vid, ibuf, sizeof( vid ));
1634     ibuf += sizeof( vid );
1635
1636     if (NULL == ( vol = getvolbyvid( vid )) ) {
1637         return( AFPERR_PARAM );
1638     }
1639
1640     if (vol->v_flags & AFPVOL_RO)
1641         return AFPERR_VLOCK;
1642
1643     memcpy( &did, ibuf, sizeof( did ));
1644     ibuf += sizeof( int );
1645
1646     if (NULL == ( dir = dirlookup( vol, did )) ) {
1647         return afp_errno;
1648     }
1649
1650     memcpy( &bitmap, ibuf, sizeof( bitmap ));
1651     bitmap = ntohs( bitmap );
1652     ibuf += sizeof( bitmap );
1653
1654     if (NULL == ( path = cname( vol, dir, &ibuf )) ) {
1655         return get_afp_errno(AFPERR_NOOBJ);
1656     }
1657
1658     if ( *path->m_name != '\0' ) {
1659         rc = path_error(path, AFPERR_NOOBJ);
1660         /* maybe we are trying to set perms back */
1661         if (rc != AFPERR_ACCESS)
1662             return rc;
1663     }
1664
1665     /*
1666      * If ibuf is odd, make it even.
1667      */
1668     if ((u_long)ibuf & 1 ) {
1669         ibuf++;
1670     }
1671
1672     if (AFP_OK == ( rc = setdirparams(vol, path, bitmap, ibuf )) ) {
1673         setvoltime(obj, vol );
1674     }
1675     return( rc );
1676 }
1677
1678 /*
1679  * cf AFP3.0.pdf page 244 for change_mdate and change_parent_mdate logic
1680  *
1681  * assume path == '\0' eg. it's a directory in canonical form
1682  */
1683 int setdirparams(struct vol *vol, struct path *path, u_int16_t d_bitmap, char *buf )
1684 {
1685     struct maccess  ma;
1686     struct adouble  ad;
1687     struct utimbuf      ut;
1688     struct timeval      tv;
1689
1690     char                *upath;
1691     struct dir          *dir;
1692     int         bit, isad = 1;
1693     int                 cdate, bdate;
1694     int                 owner, group;
1695     u_int16_t       ashort, bshort, oshort;
1696     int                 err = AFP_OK;
1697     int                 change_mdate = 0;
1698     int                 change_parent_mdate = 0;
1699     int                 newdate = 0;
1700     u_int16_t           bitmap = d_bitmap;
1701     u_char              finder_buf[32];
1702     u_int32_t       upriv;
1703     mode_t              mpriv = 0;
1704     u_int16_t           upriv_bit = 0;
1705
1706     bit = 0;
1707     upath = path->u_name;
1708     dir   = path->d_dir;
1709     while ( bitmap != 0 ) {
1710         while (( bitmap & 1 ) == 0 ) {
1711             bitmap = bitmap>>1;
1712             bit++;
1713         }
1714
1715         switch( bit ) {
1716         case DIRPBIT_ATTR :
1717             change_mdate = 1;
1718             memcpy( &ashort, buf, sizeof( ashort ));
1719             buf += sizeof( ashort );
1720             break;
1721         case DIRPBIT_CDATE :
1722             change_mdate = 1;
1723             memcpy(&cdate, buf, sizeof(cdate));
1724             buf += sizeof( cdate );
1725             break;
1726         case DIRPBIT_MDATE :
1727             memcpy(&newdate, buf, sizeof(newdate));
1728             buf += sizeof( newdate );
1729             break;
1730         case DIRPBIT_BDATE :
1731             change_mdate = 1;
1732             memcpy(&bdate, buf, sizeof(bdate));
1733             buf += sizeof( bdate );
1734             break;
1735         case DIRPBIT_FINFO :
1736             change_mdate = 1;
1737             memcpy( finder_buf, buf, 32 );
1738             buf += 32;
1739             break;
1740         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1741             change_parent_mdate = 1;
1742             memcpy( &owner, buf, sizeof(owner));
1743             buf += sizeof( owner );
1744             break;
1745         case DIRPBIT_GID :
1746             change_parent_mdate = 1;
1747             memcpy( &group, buf, sizeof( group ));
1748             buf += sizeof( group );
1749             break;
1750         case DIRPBIT_ACCESS :
1751             change_mdate = 1;
1752             change_parent_mdate = 1;
1753             ma.ma_user = *buf++;
1754             ma.ma_world = *buf++;
1755             ma.ma_group = *buf++;
1756             ma.ma_owner = *buf++;
1757             mpriv = mtoumode( &ma ) | vol->v_dperm;
1758             if (dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1759                 err = set_dir_errors(path, "setdirmode", errno);
1760                 bitmap = 0;
1761             }
1762             break;
1763             /* Ignore what the client thinks we should do to the
1764                ProDOS information block.  Skip over the data and
1765                report nothing amiss. <shirsch@ibm.net> */
1766         case DIRPBIT_PDINFO :
1767             if (afp_version < 30) {
1768                 buf += 6;
1769             }
1770             else {
1771                 err = AFPERR_BITMAP;
1772                 bitmap = 0;
1773             }
1774             break;
1775         case DIRPBIT_UNIXPR :
1776             if (vol_unix_priv(vol)) {
1777                 memcpy( &owner, buf, sizeof(owner)); /* FIXME need to change owner too? */
1778                 buf += sizeof( owner );
1779                 memcpy( &group, buf, sizeof( group ));
1780                 buf += sizeof( group );
1781
1782                 change_mdate = 1;
1783                 change_parent_mdate = 1;
1784                 memcpy( &upriv, buf, sizeof( upriv ));
1785                 buf += sizeof( upriv );
1786                 upriv = ntohl (upriv) | vol->v_dperm;
1787                 if (dir_rx_set(upriv)) {
1788                     /* maybe we are trying to set perms back */
1789                     if ( setdirunixmode(vol, upath, upriv) < 0 ) {
1790                         bitmap = 0;
1791                         err = set_dir_errors(path, "setdirunixmode", errno);
1792                     }
1793                 }
1794                 else {
1795                     /* do it later */
1796                     upriv_bit = 1;
1797                 }
1798                 break;
1799             }
1800             /* fall through */
1801         default :
1802             err = AFPERR_BITMAP;
1803             bitmap = 0;
1804             break;
1805         }
1806
1807         bitmap = bitmap>>1;
1808         bit++;
1809     }
1810     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
1811
1812     if (ad_open_metadata( upath, ADFLAGS_DIR, O_CREAT, &ad) < 0) {
1813         /*
1814          * Check to see what we're trying to set.  If it's anything
1815          * but ACCESS, UID, or GID, give an error.  If it's any of those
1816          * three, we don't need the ad to be open, so just continue.
1817          *
1818          * note: we also don't need to worry about mdate. also, be quiet
1819          *       if we're using the noadouble option.
1820          */
1821         if (!vol_noadouble(vol) && (d_bitmap &
1822                                     ~((1<<DIRPBIT_ACCESS)|(1<<DIRPBIT_UNIXPR)|
1823                                       (1<<DIRPBIT_UID)|(1<<DIRPBIT_GID)|
1824                                       (1<<DIRPBIT_MDATE)|(1<<DIRPBIT_PDINFO)))) {
1825             return AFPERR_ACCESS;
1826         }
1827
1828         isad = 0;
1829     } else {
1830         /*
1831          * Check to see if a create was necessary. If it was, we'll want
1832          * to set our name, etc.
1833          */
1834         if ( (ad_get_HF_flags( &ad ) & O_CREAT)) {
1835             ad_setname(&ad, cfrombstr(curdir->d_m_name));
1836         }
1837     }
1838
1839     bit = 0;
1840     bitmap = d_bitmap;
1841     while ( bitmap != 0 ) {
1842         while (( bitmap & 1 ) == 0 ) {
1843             bitmap = bitmap>>1;
1844             bit++;
1845         }
1846
1847         switch( bit ) {
1848         case DIRPBIT_ATTR :
1849             if (isad) {
1850                 ad_getattr(&ad, &bshort);
1851                 oshort = bshort;
1852                 if ( ntohs( ashort ) & ATTRBIT_SETCLR ) {
1853                     bshort |= htons( ntohs( ashort ) & ~ATTRBIT_SETCLR );
1854                 } else {
1855                     bshort &= ~ashort;
1856                 }
1857                 if ((bshort & htons(ATTRBIT_INVISIBLE)) != (oshort & htons(ATTRBIT_INVISIBLE)))
1858                     change_parent_mdate = 1;
1859                 ad_setattr(&ad, bshort);
1860             }
1861             break;
1862         case DIRPBIT_CDATE :
1863             if (isad) {
1864                 ad_setdate(&ad, AD_DATE_CREATE, cdate);
1865             }
1866             break;
1867         case DIRPBIT_MDATE :
1868             break;
1869         case DIRPBIT_BDATE :
1870             if (isad) {
1871                 ad_setdate(&ad, AD_DATE_BACKUP, bdate);
1872             }
1873             break;
1874         case DIRPBIT_FINFO :
1875             if (isad) {
1876                 /* Fixes #2802236 */
1877                 u_int16_t *fflags = (u_int16_t *)(finder_buf + FINDERINFO_FRFLAGOFF);
1878                 *fflags &= htons(~FINDERINFO_ISHARED);
1879                 /* #2802236 end */
1880                 if (  dir->d_did == DIRDID_ROOT ) {
1881                     /*
1882                      * Alright, we admit it, this is *really* sick!
1883                      * The 4 bytes that we don't copy, when we're dealing
1884                      * with the root of a volume, are the directory's
1885                      * location information. This eliminates that annoying
1886                      * behavior one sees when mounting above another mount
1887                      * point.
1888                      */
1889                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 10 );
1890                     memcpy( ad_entry( &ad, ADEID_FINDERI ) + 14, finder_buf + 14, 18 );
1891                 } else {
1892                     memcpy( ad_entry( &ad, ADEID_FINDERI ), finder_buf, 32 );
1893                 }
1894             }
1895             break;
1896         case DIRPBIT_UID :  /* What kind of loser mounts as root? */
1897             if ( (dir->d_did == DIRDID_ROOT) &&
1898                  (setdeskowner( ntohl(owner), -1 ) < 0)) {
1899                 err = set_dir_errors(path, "setdeskowner", errno);
1900                 if (isad && err == AFPERR_PARAM) {
1901                     err = AFP_OK; /* ???*/
1902                 }
1903                 else {
1904                     goto setdirparam_done;
1905                 }
1906             }
1907             if ( setdirowner(vol, upath, ntohl(owner), -1 ) < 0 ) {
1908                 err = set_dir_errors(path, "setdirowner", errno);
1909                 goto setdirparam_done;
1910             }
1911             break;
1912         case DIRPBIT_GID :
1913             if (dir->d_did == DIRDID_ROOT)
1914                 setdeskowner( -1, ntohl(group) );
1915             if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1916                 err = set_dir_errors(path, "setdirowner", errno);
1917                 goto setdirparam_done;
1918             }
1919             break;
1920         case DIRPBIT_ACCESS :
1921             if (dir->d_did == DIRDID_ROOT) {
1922                 setdeskmode(mpriv);
1923                 if (!dir_rx_set(mpriv)) {
1924                     /* we can't remove read and search for owner on volume root */
1925                     err = AFPERR_ACCESS;
1926                     goto setdirparam_done;
1927                 }
1928             }
1929
1930             if (!dir_rx_set(mpriv) && setdirmode( vol, upath, mpriv) < 0 ) {
1931                 err = set_dir_errors(path, "setdirmode", errno);
1932                 goto setdirparam_done;
1933             }
1934             break;
1935         case DIRPBIT_PDINFO :
1936             if (afp_version >= 30) {
1937                 err = AFPERR_BITMAP;
1938                 goto setdirparam_done;
1939             }
1940             break;
1941         case DIRPBIT_UNIXPR :
1942             if (vol_unix_priv(vol)) {
1943                 if (dir->d_did == DIRDID_ROOT) {
1944                     if (!dir_rx_set(upriv)) {
1945                         /* we can't remove read and search for owner on volume root */
1946                         err = AFPERR_ACCESS;
1947                         goto setdirparam_done;
1948                     }
1949                     setdeskowner( -1, ntohl(group) );
1950                     setdeskmode( upriv );
1951                 }
1952                 if ( setdirowner(vol, upath, -1, ntohl(group) ) < 0 ) {
1953                     err = set_dir_errors(path, "setdirowner", errno);
1954                     goto setdirparam_done;
1955                 }
1956
1957                 if ( upriv_bit && setdirunixmode(vol, upath, upriv) < 0 ) {
1958                     err = set_dir_errors(path, "setdirunixmode", errno);
1959                     goto setdirparam_done;
1960                 }
1961             }
1962             else {
1963                 err = AFPERR_BITMAP;
1964                 goto setdirparam_done;
1965             }
1966             break;
1967         default :
1968             err = AFPERR_BITMAP;
1969             goto setdirparam_done;
1970             break;
1971         }
1972
1973         bitmap = bitmap>>1;
1974         bit++;
1975     }
1976
1977 setdirparam_done:
1978     if (change_mdate && newdate == 0 && gettimeofday(&tv, NULL) == 0) {
1979         newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
1980     }
1981     if (newdate) {
1982         if (isad)
1983             ad_setdate(&ad, AD_DATE_MODIFY, newdate);
1984         ut.actime = ut.modtime = AD_DATE_TO_UNIX(newdate);
1985         utime(upath, &ut);
1986     }
1987
1988     if ( isad ) {
1989         if (path->st_valid && !path->st_errno) {
1990             struct stat *st = &path->st;
1991
1992             if (dir && dir->d_pdid) {
1993                 ad_setid(&ad, st->st_dev, st->st_ino,  dir->d_did, dir->d_pdid, vol->v_stamp);
1994             }
1995         }
1996         ad_flush( &ad);
1997         ad_close_metadata( &ad);
1998     }
1999
2000     if (change_parent_mdate && dir->d_did != DIRDID_ROOT
2001         && gettimeofday(&tv, NULL) == 0) {
2002         if (movecwd(vol, dirlookup(vol, dir->d_pdid)) == 0) {
2003             newdate = AD_DATE_FROM_UNIX(tv.tv_sec);
2004             /* be careful with bitmap because now dir is null */
2005             bitmap = 1<<DIRPBIT_MDATE;
2006             setdirparams(vol, &Cur_Path, bitmap, (char *)&newdate);
2007             /* should we reset curdir ?*/
2008         }
2009     }
2010
2011     return err;
2012 }
2013
2014 int afp_syncdir(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2015 {
2016 #ifdef HAVE_DIRFD
2017     DIR                  *dp;
2018 #endif
2019     int                  dfd;
2020     struct vol           *vol;
2021     struct dir           *dir;
2022     u_int32_t            did;
2023     u_int16_t            vid;
2024
2025     *rbuflen = 0;
2026     ibuf += 2;
2027
2028     memcpy( &vid, ibuf, sizeof( vid ));
2029     ibuf += sizeof( vid );
2030     if (NULL == (vol = getvolbyvid( vid )) ) {
2031         return( AFPERR_PARAM );
2032     }
2033
2034     memcpy( &did, ibuf, sizeof( did ));
2035     ibuf += sizeof( did );
2036
2037     /*
2038      * Here's the deal:
2039      * if it's CNID 2 our only choice to meet the specs is call sync.
2040      * For any other CNID just sync that dir. To my knowledge the
2041      * intended use of FPSyncDir is to sync the volume so all we're
2042      * ever going to see here is probably CNID 2. Anyway, we' prepared.
2043      */
2044
2045     if ( ntohl(did) == 2 ) {
2046         sync();
2047     } else {
2048         if (NULL == ( dir = dirlookup( vol, did )) ) {
2049             return afp_errno; /* was AFPERR_NOOBJ */
2050         }
2051
2052         if (movecwd( vol, dir ) < 0 )
2053             return ( AFPERR_NOOBJ );
2054
2055         /*
2056          * Assuming only OSens that have dirfd also may require fsyncing directories
2057          * in order to flush metadata e.g. Linux.
2058          */
2059
2060 #ifdef HAVE_DIRFD
2061         if (NULL == ( dp = opendir( "." )) ) {
2062             switch( errno ) {
2063             case ENOENT :
2064                 return( AFPERR_NOOBJ );
2065             case EACCES :
2066                 return( AFPERR_ACCESS );
2067             default :
2068                 return( AFPERR_PARAM );
2069             }
2070         }
2071
2072         LOG(log_debug, logtype_afpd, "afp_syncdir: dir: '%s'", dir->d_u_name);
2073
2074         dfd = dirfd( dp );
2075         if ( fsync ( dfd ) < 0 )
2076             LOG(log_error, logtype_afpd, "afp_syncdir(%s):  %s",
2077                 dir->d_u_name, strerror(errno) );
2078         closedir(dp); /* closes dfd too */
2079 #endif
2080
2081         if ( -1 == (dfd = open(vol->ad_path(".", ADFLAGS_DIR), O_RDWR))) {
2082             switch( errno ) {
2083             case ENOENT:
2084                 return( AFPERR_NOOBJ );
2085             case EACCES:
2086                 return( AFPERR_ACCESS );
2087             default:
2088                 return( AFPERR_PARAM );
2089             }
2090         }
2091
2092         LOG(log_debug, logtype_afpd, "afp_syncdir: ad-file: '%s'",
2093             vol->ad_path(".", ADFLAGS_DIR) );
2094
2095         if ( fsync(dfd) < 0 )
2096             LOG(log_error, logtype_afpd, "afp_syncdir(%s): %s",
2097                 vol->ad_path(cfrombstr(dir->d_u_name), ADFLAGS_DIR), strerror(errno) );
2098         close(dfd);
2099     }
2100
2101     return ( AFP_OK );
2102 }
2103
2104 int afp_createdir(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2105 {
2106     struct adouble  ad;
2107     struct vol      *vol;
2108     struct dir      *dir;
2109     char        *upath;
2110     struct path         *s_path;
2111     u_int32_t       did;
2112     u_int16_t       vid;
2113     int                 err;
2114
2115     *rbuflen = 0;
2116     ibuf += 2;
2117
2118     memcpy( &vid, ibuf, sizeof( vid ));
2119     ibuf += sizeof( vid );
2120     if (NULL == ( vol = getvolbyvid( vid )) ) {
2121         return( AFPERR_PARAM );
2122     }
2123
2124     if (vol->v_flags & AFPVOL_RO)
2125         return AFPERR_VLOCK;
2126
2127     memcpy( &did, ibuf, sizeof( did ));
2128     ibuf += sizeof( did );
2129     if (NULL == ( dir = dirlookup( vol, did )) ) {
2130         return afp_errno; /* was AFPERR_NOOBJ */
2131     }
2132     /* for concurrent access we need to be sure we are not in the
2133      * folder we want to create...
2134      */
2135     movecwd(vol, dir);
2136
2137     if (NULL == ( s_path = cname( vol, dir, &ibuf )) ) {
2138         return get_afp_errno(AFPERR_PARAM);
2139     }
2140     /* cname was able to move curdir to it! */
2141     if (*s_path->m_name == '\0')
2142         return AFPERR_EXIST;
2143
2144     upath = s_path->u_name;
2145
2146     if (AFP_OK != (err = netatalk_mkdir(vol, upath))) {
2147         return err;
2148     }
2149
2150     if (of_stat(s_path) < 0) {
2151         return AFPERR_MISC;
2152     }
2153
2154     curdir->offcnt++;
2155
2156     if ((dir = dir_add(vol, curdir, s_path, strlen(s_path->u_name))) == NULL) {
2157         return AFPERR_MISC;
2158     }
2159
2160     if ( movecwd( vol, dir ) < 0 ) {
2161         return( AFPERR_PARAM );
2162     }
2163
2164     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2165     if (ad_open_metadata( ".", ADFLAGS_DIR, O_CREAT, &ad ) < 0)  {
2166         if (vol_noadouble(vol))
2167             goto createdir_done;
2168         return( AFPERR_ACCESS );
2169     }
2170     ad_setname(&ad, s_path->m_name);
2171     ad_setid( &ad, s_path->st.st_dev, s_path->st.st_ino, dir->d_did, did, vol->v_stamp);
2172
2173     ad_flush( &ad);
2174     ad_close_metadata( &ad);
2175
2176 createdir_done:
2177     memcpy( rbuf, &dir->d_did, sizeof( u_int32_t ));
2178     *rbuflen = sizeof( u_int32_t );
2179     setvoltime(obj, vol );
2180     return( AFP_OK );
2181 }
2182
2183 /*
2184  * dst       new unix filename (not a pathname)
2185  * newname   new mac name
2186  * newparent curdir
2187  * dirfd     -1 means ignore dirfd (or use AT_FDCWD), otherwise src is relative to dirfd
2188  */
2189 int renamedir(const struct vol *vol,
2190               int dirfd,
2191               char *src,
2192               char *dst,
2193               struct dir *dir,
2194               struct dir *newparent,
2195               char *newname)
2196 {
2197     struct adouble  ad;
2198     int             err;
2199
2200     /* existence check moved to afp_moveandrename */
2201     if ( unix_rename(dirfd, src, -1, dst ) < 0 ) {
2202         switch ( errno ) {
2203         case ENOENT :
2204             return( AFPERR_NOOBJ );
2205         case EACCES :
2206             return( AFPERR_ACCESS );
2207         case EROFS:
2208             return AFPERR_VLOCK;
2209         case EINVAL:
2210             /* tried to move directory into a subdirectory of itself */
2211             return AFPERR_CANTMOVE;
2212         case EXDEV:
2213             /* this needs to copy and delete. bleah. that means we have
2214              * to deal with entire directory hierarchies. */
2215             if ((err = copydir(vol, dirfd, src, dst)) < 0) {
2216                 deletedir(-1, dst);
2217                 return err;
2218             }
2219             if ((err = deletedir(dirfd, src)) < 0)
2220                 return err;
2221             break;
2222         default :
2223             return( AFPERR_PARAM );
2224         }
2225     }
2226
2227     vol->vfs->vfs_renamedir(vol, dirfd, src, dst);
2228
2229     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2230
2231     if (!ad_open_metadata( dst, ADFLAGS_DIR, 0, &ad)) {
2232         ad_setname(&ad, newname);
2233         ad_flush( &ad);
2234         ad_close_metadata( &ad);
2235     }
2236
2237     return( AFP_OK );
2238 }
2239
2240 /* delete an empty directory */
2241 int deletecurdir(struct vol *vol)
2242 {
2243     struct dirent *de;
2244     struct stat st;
2245     struct dir  *fdir;
2246     DIR *dp;
2247     struct adouble  ad;
2248     u_int16_t       ashort;
2249     int err;
2250
2251     if ( dirlookup(vol, curdir->d_pdid) == NULL ) {
2252         return( AFPERR_ACCESS );
2253     }
2254
2255     fdir = curdir;
2256
2257     ad_init(&ad, vol->v_adouble, vol->v_ad_options);
2258     /* we never want to create a resource fork here, we are going to delete it */
2259     if ( ad_metadata( ".", ADFLAGS_DIR, &ad) == 0 ) {
2260
2261         ad_getattr(&ad, &ashort);
2262         ad_close_metadata(&ad);
2263         if ((ashort & htons(ATTRBIT_NODELETE))) {
2264             return  AFPERR_OLOCK;
2265         }
2266     }
2267     err = vol->vfs->vfs_deletecurdir(vol);
2268     if (err) {
2269         return err;
2270     }
2271
2272     /* now get rid of dangling symlinks */
2273     if ((dp = opendir("."))) {
2274         while ((de = readdir(dp))) {
2275             /* skip this and previous directory */
2276             if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
2277                 continue;
2278
2279             /* bail if it's not a symlink */
2280             if ((lstat(de->d_name, &st) == 0) && !S_ISLNK(st.st_mode)) {
2281                 closedir(dp);
2282                 return AFPERR_DIRNEMPT;
2283             }
2284
2285             if ((err = netatalk_unlink(de->d_name))) {
2286                 closedir(dp);
2287                 return err;
2288             }
2289         }
2290     }
2291
2292     if ( movecwd(vol, dirlookup(vol, curdir->d_pdid)) < 0 ) {
2293         err = afp_errno;
2294         goto delete_done;
2295     }
2296
2297     err = netatalk_rmdir_all_errors(-1, cfrombstr(fdir->d_u_name));
2298     if ( err ==  AFP_OK || err == AFPERR_NOOBJ) {
2299         cnid_delete(vol->v_cdb, fdir->d_did);
2300         dir_remove( vol, fdir );
2301     }
2302 delete_done:
2303     if (dp) {
2304         /* inode is used as key for cnid.
2305          * Close the descriptor only after cnid_delete
2306          * has been called.
2307          */
2308         closedir(dp);
2309     }
2310     return err;
2311 }
2312
2313 int afp_mapid(AFPObj *obj, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2314 {
2315     struct passwd   *pw;
2316     struct group    *gr;
2317     char        *name;
2318     u_int32_t           id;
2319     int         len, sfunc;
2320     int         utf8 = 0;
2321
2322     ibuf++;
2323     sfunc = (unsigned char) *ibuf++;
2324     *rbuflen = 0;
2325
2326     if (sfunc >= 3 && sfunc <= 6) {
2327         if (afp_version < 30) {
2328             return( AFPERR_PARAM );
2329         }
2330         utf8 = 1;
2331     }
2332
2333     switch ( sfunc ) {
2334     case 1 :
2335     case 3 :/* unicode */
2336         memcpy( &id, ibuf, sizeof( id ));
2337         id = ntohl(id);
2338         if ( id != 0 ) {
2339             if (( pw = getpwuid( id )) == NULL ) {
2340                 return( AFPERR_NOITEM );
2341             }
2342             len = convert_string_allocate( obj->options.unixcharset, ((!utf8)?obj->options.maccharset:CH_UTF8_MAC),
2343                                            pw->pw_name, -1, &name);
2344         } else {
2345             len = 0;
2346             name = NULL;
2347         }
2348         break;
2349     case 2 :
2350     case 4 : /* unicode */
2351         memcpy( &id, ibuf, sizeof( id ));
2352         id = ntohl(id);
2353         if ( id != 0 ) {
2354             if (NULL == ( gr = (struct group *)getgrgid( id ))) {
2355                 return( AFPERR_NOITEM );
2356             }
2357             len = convert_string_allocate( obj->options.unixcharset, (!utf8)?obj->options.maccharset:CH_UTF8_MAC,
2358                                            gr->gr_name, -1, &name);
2359         } else {
2360             len = 0;
2361             name = NULL;
2362         }
2363         break;
2364
2365     case 5 : /* UUID -> username */
2366     case 6 : /* UUID -> groupname */
2367         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2368             return AFPERR_PARAM;
2369         LOG(log_debug, logtype_afpd, "afp_mapid: valid UUID request");
2370         uuidtype_t type;
2371         len = getnamefromuuid((unsigned char*) ibuf, &name, &type);
2372         if (len != 0)       /* its a error code, not len */
2373             return AFPERR_NOITEM;
2374         switch (type) {
2375         case UUID_USER:
2376             if (( pw = getpwnam( name )) == NULL )
2377                 return( AFPERR_NOITEM );
2378             LOG(log_debug, logtype_afpd, "afp_mapid: name:%s -> uid:%d", name, pw->pw_uid);
2379             id = htonl(UUID_USER);
2380             memcpy( rbuf, &id, sizeof( id ));
2381             id = htonl( pw->pw_uid);
2382             rbuf += sizeof( id );
2383             memcpy( rbuf, &id, sizeof( id ));
2384             rbuf += sizeof( id );
2385             *rbuflen = 2 * sizeof( id );
2386             break;
2387         case UUID_GROUP:
2388             if (( gr = getgrnam( name )) == NULL )
2389                 return( AFPERR_NOITEM );
2390             LOG(log_debug, logtype_afpd, "afp_mapid: group:%s -> gid:%d", name, gr->gr_gid);
2391             id = htonl(UUID_GROUP);
2392             memcpy( rbuf, &id, sizeof( id ));
2393             rbuf += sizeof( id );
2394             id = htonl( gr->gr_gid);
2395             memcpy( rbuf, &id, sizeof( id ));
2396             rbuf += sizeof( id );
2397             *rbuflen = 2 * sizeof( id );
2398             break;
2399         case UUID_LOCAL:
2400             free(name);
2401             return (AFPERR_NOITEM);
2402         default:
2403             return AFPERR_MISC;
2404         }
2405         break;
2406
2407     default :
2408         return( AFPERR_PARAM );
2409     }
2410
2411     if (name)
2412         len = strlen( name );
2413
2414     if (utf8) {
2415         u_int16_t tp = htons(len);
2416         memcpy(rbuf, &tp, sizeof(tp));
2417         rbuf += sizeof(tp);
2418         *rbuflen += 2;
2419     }
2420     else {
2421         *rbuf++ = len;
2422         *rbuflen += 1;
2423     }
2424     if ( len > 0 ) {
2425         memcpy( rbuf, name, len );
2426     }
2427     *rbuflen += len;
2428     if (name)
2429         free(name);
2430     return( AFP_OK );
2431 }
2432
2433 int afp_mapname(AFPObj *obj _U_, char *ibuf, size_t ibuflen _U_, char *rbuf, size_t *rbuflen)
2434 {
2435     struct passwd   *pw;
2436     struct group    *gr;
2437     int             len, sfunc;
2438     u_int32_t       id;
2439     u_int16_t       ulen;
2440
2441     ibuf++;
2442     sfunc = (unsigned char) *ibuf++;
2443     *rbuflen = 0;
2444     LOG(log_debug, logtype_afpd, "afp_mapname: sfunc: %d, afp_version: %d", sfunc, afp_version);
2445     switch ( sfunc ) {
2446     case 1 :
2447     case 2 : /* unicode */
2448         if (afp_version < 30) {
2449             return( AFPERR_PARAM );
2450         }
2451         memcpy(&ulen, ibuf, sizeof(ulen));
2452         len = ntohs(ulen);
2453         ibuf += 2;
2454         LOG(log_debug, logtype_afpd, "afp_mapname: alive");
2455         break;
2456     case 3 :
2457     case 4 :
2458         len = (unsigned char) *ibuf++;
2459         break;
2460     case 5 : /* username -> UUID  */
2461     case 6 : /* groupname -> UUID */
2462         if ((afp_version < 32) || !(obj->options.flags & OPTION_UUID ))
2463             return AFPERR_PARAM;
2464         memcpy(&ulen, ibuf, sizeof(ulen));
2465         len = ntohs(ulen);
2466         ibuf += 2;
2467         break;
2468     default :
2469         return( AFPERR_PARAM );
2470     }
2471
2472     ibuf[ len ] = '\0';
2473
2474     if ( len == 0 )
2475         return AFPERR_PARAM;
2476     else {
2477         switch ( sfunc ) {
2478         case 1 : /* unicode */
2479         case 3 :
2480             if (NULL == ( pw = (struct passwd *)getpwnam( ibuf )) ) {
2481                 return( AFPERR_NOITEM );
2482             }
2483             id = pw->pw_uid;
2484             id = htonl(id);
2485             memcpy( rbuf, &id, sizeof( id ));
2486             *rbuflen = sizeof( id );
2487             break;
2488
2489         case 2 : /* unicode */
2490         case 4 :
2491             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s",ibuf);
2492             if (NULL == ( gr = (struct group *)getgrnam( ibuf ))) {
2493                 return( AFPERR_NOITEM );
2494             }
2495             id = gr->gr_gid;
2496             LOG(log_debug, logtype_afpd, "afp_mapname: gettgrnam for name: %s -> id: %d",ibuf, id);
2497             id = htonl(id);
2498             memcpy( rbuf, &id, sizeof( id ));
2499             *rbuflen = sizeof( id );
2500             break;
2501         case 5 :        /* username -> UUID */
2502             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2503             if (0 != getuuidfromname(ibuf, UUID_USER, (unsigned char *)rbuf))
2504                 return AFPERR_NOITEM;
2505             *rbuflen = UUID_BINSIZE;
2506             break;
2507         case 6 :        /* groupname -> UUID */
2508             LOG(log_debug, logtype_afpd, "afp_mapname: name: %s",ibuf);
2509             if (0 != getuuidfromname(ibuf, UUID_GROUP, (unsigned char *)rbuf))
2510                 return AFPERR_NOITEM;
2511             *rbuflen = UUID_BINSIZE;
2512             break;
2513         }
2514     }
2515     return( AFP_OK );
2516 }
2517
2518 /* ------------------------------------
2519    variable DID support
2520 */
2521 int afp_closedir(AFPObj *obj _U_, char *ibuf _U_, size_t ibuflen _U_, char *rbuf _U_, size_t *rbuflen)
2522 {
2523 #if 0
2524     struct vol   *vol;
2525     struct dir   *dir;
2526     u_int16_t    vid;
2527     u_int32_t    did;
2528 #endif /* 0 */
2529
2530     *rbuflen = 0;
2531
2532     /* do nothing as dids are static for the life of the process. */
2533 #if 0
2534     ibuf += 2;
2535
2536     memcpy(&vid,  ibuf, sizeof( vid ));
2537     ibuf += sizeof( vid );
2538     if (( vol = getvolbyvid( vid )) == NULL ) {
2539         return( AFPERR_PARAM );
2540     }
2541
2542     memcpy( &did, ibuf, sizeof( did ));
2543     ibuf += sizeof( did );
2544     if (( dir = dirlookup( vol, did )) == NULL ) {
2545         return( AFPERR_PARAM );
2546     }
2547
2548     /* dir_remove -- deletedid */
2549 #endif /* 0 */
2550
2551     return AFP_OK;
2552 }
2553
2554 /* did creation gets done automatically
2555  * there's a pb again with case but move it to cname
2556  */
2557 int afp_opendir(AFPObj *obj _U_, char *ibuf, size_t ibuflen  _U_, char *rbuf, size_t *rbuflen)
2558 {
2559     struct vol      *vol;
2560     struct dir      *parentdir;
2561     struct path     *path;
2562     u_int32_t       did;
2563     u_int16_t       vid;
2564
2565     *rbuflen = 0;
2566     ibuf += 2;
2567
2568     memcpy(&vid, ibuf, sizeof(vid));
2569     ibuf += sizeof( vid );
2570
2571     if (NULL == ( vol = getvolbyvid( vid )) ) {
2572         return( AFPERR_PARAM );
2573     }
2574
2575     memcpy(&did, ibuf, sizeof(did));
2576     ibuf += sizeof(did);
2577
2578     if (NULL == ( parentdir = dirlookup( vol, did )) ) {
2579         return afp_errno;
2580     }
2581
2582     if (NULL == ( path = cname( vol, parentdir, &ibuf )) ) {
2583         return get_afp_errno(AFPERR_PARAM);
2584     }
2585
2586     if ( *path->m_name != '\0' ) {
2587         return path_error(path, AFPERR_NOOBJ);
2588     }
2589
2590     if ( !path->st_valid && of_stat(path ) < 0 ) {
2591         return( AFPERR_NOOBJ );
2592     }
2593     if ( path->st_errno ) {
2594         return( AFPERR_NOOBJ );
2595     }
2596
2597     memcpy(rbuf, &curdir->d_did, sizeof(curdir->d_did));
2598     *rbuflen = sizeof(curdir->d_did);
2599     return AFP_OK;
2600 }