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