Windows: CellLength reported in octets
[openafs.git] / src / WINNT / afsrdr / user / RDRFunction.c
1 /*
2  * Copyright (c) 2008 Secure Endpoints, Inc.
3  * Copyright (c) 2009-2011 Your File System, Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * - Redistributions of source code must retain the above copyright notice,
10  *   this list of conditions and the following disclaimer.
11  * - Redistributions in binary form must reproduce the above copyright notice,
12  *   this list of conditions and the following disclaimer in the documentation
13  *   and/or other materials provided with the distribution.
14  * - Neither the name of Secure Endpoints Inc. nor the names of its contributors
15  *   may be used to endorse or promote products derived from this software without
16  *   specific prior written permission from Secure Endpoints, Inc. and
17  *   Your File System, Inc.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
23  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <afsconfig.h>
33 #include <afs/param.h>
34
35 #ifndef _WIN32_WINNT
36 #define _WIN32_WINNT 0x0500
37 #endif
38 #define _CRT_SECURE_NO_DEPRECATE
39 #define _CRT_NON_CONFORMING_SWPRINTFS
40 #define INITGUID        /* define AFS_AUTH_GUID_NO_PAG */
41
42 #include <ntstatus.h>
43 #define WIN32_NO_STATUS
44 #include <windows.h>
45
46 #include <roken.h>
47
48 #include <afs/stds.h>
49
50 #include <ntsecapi.h>
51 #include <sddl.h>
52 #pragma warning(push)
53 #pragma warning(disable: 4005)
54
55 #include <devioctl.h>
56
57 #include "..\\Common\\AFSUserDefines.h"
58 #include "..\\Common\\AFSUserStructs.h"
59
60 #pragma warning(pop)
61
62 #include <tchar.h>
63 #include <wchar.h>
64 #include <winbase.h>
65 #include <winreg.h>
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <stdarg.h>
70 #include <strsafe.h>
71
72 #include "afsd.h"
73 #include "smb.h"
74 #include "cm_btree.h"
75 #include "msrpc.h"
76 #include <RDRPrototypes.h>
77 #include <RDRIoctl.h>
78 #include <RDRPipe.h>
79
80 static CHAR * RDR_extentBaseAddress = NULL;
81
82 void
83 RDR_InitReq(cm_req_t *reqp, BOOL bWow64)
84 {
85     cm_InitReq(reqp);
86     reqp->flags |= CM_REQ_SOURCE_REDIR;
87     if (bWow64)
88         reqp->flags |= CM_REQ_WOW64;
89 }
90
91 void
92 RDR_fid2FID( cm_fid_t *fid, AFSFileID *FileId)
93 {
94     FileId->Cell = fid->cell;
95     FileId->Volume = fid->volume;
96     FileId->Vnode = fid->vnode;
97     FileId->Unique = fid->unique;
98     FileId->Hash = fid->hash;
99 }
100
101 void
102 RDR_FID2fid( AFSFileID *FileId, cm_fid_t *fid)
103 {
104     fid->cell = FileId->Cell;
105     fid->volume = FileId->Volume;
106     fid->vnode = FileId->Vnode;
107     fid->unique = FileId->Unique;
108     fid->hash = FileId->Hash;
109 }
110
111 DWORD
112 RDR_SetInitParams( OUT AFSRedirectorInitInfo **ppRedirInitInfo, OUT DWORD * pRedirInitInfoLen )
113 {
114     extern char cm_CachePath[];
115     extern cm_config_data_t cm_data;
116     extern int smb_hideDotFiles;
117     size_t CachePathLen;
118     DWORD TempPathLen;
119     size_t err;
120     MEMORYSTATUSEX memStatus;
121     DWORD maxMemoryCacheSize;
122     char FullCachePath[MAX_PATH];
123     char TempPath[MAX_PATH];
124     char FullTempPath[MAX_PATH];
125
126     /*
127      * The %TEMP% environment variable may be relative instead
128      * of absolute which can result in the redirector referring
129      * to a different directory than the service.  The full path
130      * must therefore be obtained first.
131      */
132
133     CachePathLen = GetFullPathNameA(cm_CachePath, MAX_PATH, FullCachePath, NULL);
134     if (CachePathLen == 0) {
135         osi_Log0(afsd_logp, "RDR_SetInitParams Unable to obtain Full Cache Path");
136         return STATUS_OBJECT_NAME_NOT_FOUND;
137     }
138
139     TempPathLen = ExpandEnvironmentStringsA("%TEMP%", TempPath, MAX_PATH);
140     if (TempPathLen == 0) {
141         osi_Log0(afsd_logp, "RDR_SetInitParams Unable to expand %%TEMP%%");
142         return STATUS_OBJECT_NAME_NOT_FOUND;
143     }
144
145     TempPathLen = GetFullPathNameA(TempPath, MAX_PATH, FullTempPath, NULL);
146     if (TempPathLen == 0) {
147         osi_Log0(afsd_logp, "RDR_SetInitParams Unable to obtain Full Temp Path");
148         return STATUS_OBJECT_NAME_NOT_FOUND;
149     }
150
151     memStatus.dwLength = sizeof(memStatus);
152     if (GlobalMemoryStatusEx(&memStatus)) {
153         /*
154          * Use the memory extent interface in the afs redirector
155          * whenever the cache size is less than equal to 10% of
156          * physical memory.  Do not use too much because this memory
157          * will be locked by the redirector so it can't be swapped
158          * out.
159          */
160         maxMemoryCacheSize = (DWORD)(memStatus.ullTotalPhys / 1024 / 10);
161     } else {
162         /*
163          * If we can't determine the amount of physical memory
164          * in the system, be conservative and limit the use of
165          * memory extent interface to 64MB data caches.
166          */
167         maxMemoryCacheSize = 65536;
168     }
169
170     *pRedirInitInfoLen = (DWORD) (sizeof(AFSRedirectorInitInfo) + (CachePathLen + TempPathLen) * sizeof(WCHAR));
171     *ppRedirInitInfo = (AFSRedirectorInitInfo *)malloc(*pRedirInitInfoLen);
172     (*ppRedirInitInfo)->Flags = smb_hideDotFiles ? AFS_REDIR_INIT_FLAG_HIDE_DOT_FILES : 0;
173     (*ppRedirInitInfo)->Flags |= cm_shortNames ? 0 : AFS_REDIR_INIT_FLAG_DISABLE_SHORTNAMES;
174     (*ppRedirInitInfo)->MaximumChunkLength = cm_data.chunkSize;
175     (*ppRedirInitInfo)->GlobalFileId.Cell   = cm_data.rootFid.cell;
176     (*ppRedirInitInfo)->GlobalFileId.Volume = cm_data.rootFid.volume;
177     (*ppRedirInitInfo)->GlobalFileId.Vnode  = cm_data.rootFid.vnode;
178     (*ppRedirInitInfo)->GlobalFileId.Unique = cm_data.rootFid.unique;
179     (*ppRedirInitInfo)->GlobalFileId.Hash   = cm_data.rootFid.hash;
180     (*ppRedirInitInfo)->ExtentCount.QuadPart = cm_data.buf_nbuffers;
181     (*ppRedirInitInfo)->CacheBlockSize = cm_data.blockSize;
182     (*ppRedirInitInfo)->MaxPathLinkCount = MAX_FID_COUNT;
183     (*ppRedirInitInfo)->NameArrayLength = MAX_FID_COUNT;
184     if (cm_virtualCache || cm_data.bufferSize <= maxMemoryCacheSize) {
185         osi_Log0(afsd_logp, "RDR_SetInitParams Initializing Memory Extent Interface");
186         (*ppRedirInitInfo)->MemoryCacheOffset.QuadPart = (LONGLONG)cm_data.bufDataBaseAddress;
187         (*ppRedirInitInfo)->MemoryCacheLength.QuadPart = cm_data.bufEndOfData - cm_data.bufDataBaseAddress;
188         (*ppRedirInitInfo)->CacheFileNameLength = 0;
189         RDR_extentBaseAddress = cm_data.bufDataBaseAddress;
190     } else {
191         (*ppRedirInitInfo)->MemoryCacheOffset.QuadPart = 0;
192         (*ppRedirInitInfo)->MemoryCacheLength.QuadPart = 0;
193         (*ppRedirInitInfo)->CacheFileNameLength = (ULONG) (CachePathLen * sizeof(WCHAR));
194         err = mbstowcs((*ppRedirInitInfo)->CacheFileName, FullCachePath, (CachePathLen + 1) *sizeof(WCHAR));
195         if (err == -1) {
196             free(*ppRedirInitInfo);
197             osi_Log0(afsd_logp, "RDR_SetInitParams Invalid Object Name");
198             return STATUS_OBJECT_NAME_INVALID;
199         }
200         RDR_extentBaseAddress = cm_data.baseAddress;
201     }
202     (*ppRedirInitInfo)->DumpFileLocationOffset = FIELD_OFFSET(AFSRedirectorInitInfo, CacheFileName) + (*ppRedirInitInfo)->CacheFileNameLength;
203     (*ppRedirInitInfo)->DumpFileLocationLength = (TempPathLen - 1) * sizeof(WCHAR);
204
205     err = mbstowcs((((PBYTE)(*ppRedirInitInfo)) + (*ppRedirInitInfo)->DumpFileLocationOffset),
206                    FullTempPath, (TempPathLen + 1) *sizeof(WCHAR));
207     if (err == -1) {
208         free(*ppRedirInitInfo);
209         osi_Log0(afsd_logp, "RDR_SetInitParams Invalid Object Name");
210         return STATUS_OBJECT_NAME_INVALID;
211     }
212
213     osi_Log0(afsd_logp,"RDR_SetInitParams Success");
214     return 0;
215 }
216
217 static wchar_t cname[MAX_COMPUTERNAME_LENGTH+1] = L"";
218
219 cm_user_t *
220 RDR_GetLocalSystemUser( void)
221 {
222     smb_username_t *unp;
223     cm_user_t *userp = NULL;
224
225     if ( cname[0] == '\0') {
226         int len = MAX_COMPUTERNAME_LENGTH+1;
227         GetComputerNameW(cname, &len);
228         _wcsupr(cname);
229     }
230     unp = smb_FindUserByName(NTSID_LOCAL_SYSTEM, cname, SMB_FLAG_CREATE);
231     lock_ObtainMutex(&unp->mx);
232     if (!unp->userp)
233         unp->userp = cm_NewUser();
234     unp->flags |= SMB_USERNAMEFLAG_SID;
235     lock_ReleaseMutex(&unp->mx);
236     userp = unp->userp;
237     cm_HoldUser(userp);
238     smb_ReleaseUsername(unp);
239
240     if (!userp) {
241         userp = cm_rootUserp;
242         cm_HoldUser(userp);
243     }
244
245     return userp;
246 }
247
248 cm_user_t *
249 RDR_UserFromCommRequest( IN AFSCommRequest *RequestBuffer)
250 {
251
252     return RDR_UserFromAuthGroup( &RequestBuffer->AuthGroup);
253 }
254
255 cm_user_t *
256 RDR_UserFromAuthGroup( IN GUID *pGuid)
257 {
258     smb_username_t *unp;
259     cm_user_t * userp = NULL;
260     RPC_WSTR UuidString = NULL;
261
262     if (UuidToStringW((UUID *)pGuid, &UuidString) != RPC_S_OK)
263         goto done;
264
265     if ( cname[0] == '\0') {
266         int len = MAX_COMPUTERNAME_LENGTH+1;
267         GetComputerNameW(cname, &len);
268         _wcsupr(cname);
269     }
270
271     unp = smb_FindUserByName(UuidString, cname, SMB_FLAG_CREATE);
272     lock_ObtainMutex(&unp->mx);
273     if (!unp->userp) {
274         unp->userp = cm_NewUser();
275         memcpy(&unp->userp->authgroup, pGuid, sizeof(GUID));
276     }
277     unp->flags |= SMB_USERNAMEFLAG_SID;
278     lock_ReleaseMutex(&unp->mx);
279     userp = unp->userp;
280     cm_HoldUser(userp);
281     smb_ReleaseUsername(unp);
282
283   done:
284     if (!userp) {
285         userp = cm_rootUserp;
286         cm_HoldUser(userp);
287     }
288
289     osi_Log2(afsd_logp, "RDR_UserFromCommRequest Guid %S userp = 0x%p",
290              osi_LogSaveStringW(afsd_logp, UuidString),
291              userp);
292
293     if (UuidString)
294         RpcStringFreeW(&UuidString);
295
296     return userp;
297 }
298
299 void
300 RDR_ReleaseUser( IN cm_user_t *userp )
301 {
302     osi_Log1(afsd_logp, "RDR_ReleaseUser userp = 0x%p", userp);
303     cm_ReleaseUser(userp);
304 }
305
306
307 /*
308  * RDR_FlagScpInUse flags the scp with CM_SCACHEFLAG_RDR_IN_USE
309  */
310 static void
311 RDR_FlagScpInUse( IN cm_scache_t *scp, IN BOOL bLocked )
312 {
313     if (!bLocked)
314         lock_ObtainWrite(&scp->rw);
315
316     lock_AssertWrite(&scp->rw);
317     scp->flags |= CM_SCACHEFLAG_RDR_IN_USE;
318
319     if (!bLocked)
320         lock_ReleaseWrite(&scp->rw);
321 }
322
323 /*
324  * Obtain the status information for the specified object using
325  * an inline bulk status rpc.  cm_BPlusDirEnumBulkStatOne() will
326  * obtain current status for the directory object, the object
327  * which is the focus of the inquiry and as many other objects
328  * in the directory for which there are not callbacks registered
329  * since we are likely to be asked for other objects in the directory.
330  */
331 static afs_uint32
332 RDR_BulkStatLookup( cm_scache_t *dscp,
333                     cm_scache_t *scp,
334                     cm_user_t   *userp,
335                     cm_req_t    *reqp)
336 {
337     cm_direnum_t *      enump = NULL;
338     afs_uint32  code = 0;
339     cm_dirOp_t    dirop;
340
341     code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
342     if (code == 0) {
343         code = cm_BPlusDirEnumerate(dscp, userp, reqp, TRUE, NULL, TRUE, &enump);
344         if (code) {
345             osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BPlusDirEnumerate failure code=0x%x",
346                       code);
347         }
348         cm_EndDirOp(&dirop);
349     } else {
350         osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BeginDirOp failure code=0x%x",
351                   code);
352     }
353
354     if (enump)
355     {
356         code = cm_BPlusDirEnumBulkStatOne(enump, scp);
357         if (code) {
358             osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BPlusDirEnumBulkStatOne failure code=0x%x",
359                       code);
360         }
361         cm_BPlusDirFreeEnumeration(enump);
362     }
363
364     return code;
365 }
366
367
368 #define RDR_POP_FOLLOW_MOUNTPOINTS 0x01
369 #define RDR_POP_EVALUATE_SYMLINKS  0x02
370 #define RDR_POP_WOW64              0x04
371 #define RDR_POP_NO_GETSTATUS       0x08
372
373 static afs_uint32
374 RDR_PopulateCurrentEntry( IN  AFSDirEnumEntry * pCurrentEntry,
375                           IN  DWORD             dwMaxEntryLength,
376                           IN  cm_scache_t     * dscp,
377                           IN  cm_scache_t     * scp,
378                           IN  cm_user_t       * userp,
379                           IN  cm_req_t        * reqp,
380                           IN  wchar_t         * name,
381                           IN  wchar_t         * shortName,
382                           IN  DWORD             dwFlags,
383                           IN  afs_uint32        cmError,
384                           OUT AFSDirEnumEntry **ppNextEntry,
385                           OUT DWORD           * pdwRemainingLength)
386 {
387     FILETIME ft;
388     WCHAR *  wname, *wtarget;
389     size_t   len;
390     DWORD      dwEntryLength;
391     afs_uint32 code = 0, code2 = 0;
392     BOOL          bMustFake = FALSE;
393
394     osi_Log5(afsd_logp, "RDR_PopulateCurrentEntry dscp=0x%p scp=0x%p name=%S short=%S flags=0x%x",
395              dscp, scp, osi_LogSaveStringW(afsd_logp, name),
396              osi_LogSaveStringW(afsd_logp, shortName), dwFlags);
397     osi_Log1(afsd_logp, "... maxLength=%d", dwMaxEntryLength);
398
399     if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
400         if (ppNextEntry)
401             *ppNextEntry = pCurrentEntry;
402         if (pdwRemainingLength)
403             *pdwRemainingLength = dwMaxEntryLength;
404         osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry Not Enough Room for Entry %d < %d",
405                  dwMaxEntryLength, sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t));
406         return CM_ERROR_TOOBIG;
407     }
408
409     if (!name)
410         name = L"";
411     if (!shortName)
412         shortName = L"";
413
414     dwEntryLength = sizeof(AFSDirEnumEntry);
415
416     lock_ObtainWrite(&scp->rw);
417     if (dwFlags & RDR_POP_NO_GETSTATUS) {
418         if (!cm_HaveCallback(scp))
419             bMustFake = TRUE;
420     } else {
421 #ifdef AFS_FREELANCE_CLIENT
422         if (scp->fid.cell == AFS_FAKE_ROOT_CELL_ID && scp->fid.volume == AFS_FAKE_ROOT_VOL_ID) {
423             /*
424              * If the FID is from the Freelance Local Root always perform
425              * a single item status check.
426              */
427             code = cm_SyncOp( scp, NULL, userp, reqp, 0,
428                               CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
429             if (code) {
430                 lock_ReleaseWrite(&scp->rw);
431                 osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_SyncOp failed for scp=0x%p code=0x%x",
432                          scp, code);
433                 return code;
434             }
435         } else
436 #endif
437         {
438             /*
439              * For non-Freelance objects, check to see if we have current
440              * status information.  If not, perform a bulk status lookup of multiple
441              * entries in order to reduce the number of RPCs issued to the file server.
442              */
443             if (cm_EAccesFindEntry(userp, &scp->fid))
444                 bMustFake = TRUE;
445             else if (!cm_HaveCallback(scp)) {
446                 lock_ReleaseWrite(&scp->rw);
447                 code = RDR_BulkStatLookup(dscp, scp, userp, reqp);
448                 if (code) {
449                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry RDR_BulkStatLookup failed for scp=0x%p code=0x%x",
450                              scp, code);
451                     return code;
452                 }
453                 lock_ObtainWrite(&scp->rw);
454                 /*
455                  * RDR_BulkStatLookup can succeed but it may be the case that there
456                  * still is not valid status info.  If we get this far, generate fake
457                  * status info.
458                  */
459                 if (!cm_HaveCallback(scp))
460                     bMustFake = TRUE;
461             }
462         }
463     }
464
465     /* Populate the error code */
466     smb_MapNTError(cmError, &pCurrentEntry->NTStatus, TRUE);
467
468     /* Populate the real or fake data */
469     pCurrentEntry->FileId.Cell = scp->fid.cell;
470     pCurrentEntry->FileId.Volume = scp->fid.volume;
471     pCurrentEntry->FileId.Vnode = scp->fid.vnode;
472     pCurrentEntry->FileId.Unique = scp->fid.unique;
473     pCurrentEntry->FileId.Hash = scp->fid.hash;
474
475     pCurrentEntry->FileType = scp->fileType;
476
477     pCurrentEntry->DataVersion.QuadPart = scp->dataVersion;
478
479     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
480         scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
481         cm_LargeSearchTimeFromUnixTime(&ft, MAX_AFS_UINT32);
482     } else {
483         cm_LargeSearchTimeFromUnixTime(&ft, scp->cbExpires);
484     }
485     pCurrentEntry->Expiration.LowPart = ft.dwLowDateTime;
486     pCurrentEntry->Expiration.HighPart = ft.dwHighDateTime;
487
488     if (bMustFake) {
489         /* 1969-12-31 23:59:59 +00 */
490         ft.dwHighDateTime = 0x19DB200;
491         ft.dwLowDateTime = 0x5BB78980;
492     } else
493         cm_LargeSearchTimeFromUnixTime(&ft, scp->clientModTime);
494     pCurrentEntry->CreationTime.LowPart = ft.dwLowDateTime;
495     pCurrentEntry->CreationTime.HighPart = ft.dwHighDateTime;
496     pCurrentEntry->LastAccessTime = pCurrentEntry->CreationTime;
497     pCurrentEntry->LastWriteTime = pCurrentEntry->CreationTime;
498     pCurrentEntry->ChangeTime = pCurrentEntry->CreationTime;
499
500     pCurrentEntry->EndOfFile = scp->length;
501     pCurrentEntry->AllocationSize = scp->length;
502
503     if (bMustFake) {
504         switch (scp->fileType) {
505         case CM_SCACHETYPE_DIRECTORY:
506             pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY;
507             break;
508         case CM_SCACHETYPE_MOUNTPOINT:
509         case CM_SCACHETYPE_INVALID:
510             pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY | SMB_ATTR_REPARSE_POINT;
511             break;
512         case CM_SCACHETYPE_SYMLINK:
513             if (cm_TargetPerceivedAsDirectory(scp->mountPointStringp))
514                 pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY | SMB_ATTR_REPARSE_POINT;
515             else
516                 pCurrentEntry->FileAttributes = SMB_ATTR_REPARSE_POINT;
517             break;
518         default:
519             /* if we get here we either have a normal file
520             * or we have a file for which we have never
521             * received status info.  In this case, we can
522             * check the even/odd value of the entry's vnode.
523             * odd means it is to be treated as a directory
524             * and even means it is to be treated as a file.
525             */
526             if (scp->fid.vnode & 0x1)
527                 pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY;
528             else
529                 pCurrentEntry->FileAttributes = SMB_ATTR_NORMAL;
530         }
531     } else
532         pCurrentEntry->FileAttributes = smb_ExtAttributes(scp);
533     pCurrentEntry->EaSize = 0;
534     pCurrentEntry->Links = scp->linkCount;
535
536     len = wcslen(shortName);
537     wcsncpy(pCurrentEntry->ShortName, shortName, len);
538     pCurrentEntry->ShortNameLength = (CCHAR)(len * sizeof(WCHAR));
539
540     pCurrentEntry->FileNameOffset = sizeof(AFSDirEnumEntry);
541     len = wcslen(name);
542     wname = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->FileNameOffset);
543     wcsncpy(wname, name, len);
544     pCurrentEntry->FileNameLength = (ULONG)(sizeof(WCHAR) * len);
545
546     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntry scp=0x%p fileType=%d dv=%u",
547               scp, scp->fileType, (afs_uint32)scp->dataVersion);
548
549     if (!(dwFlags & RDR_POP_NO_GETSTATUS))
550         cm_SyncOpDone( scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
551
552     if ((dwFlags & RDR_POP_NO_GETSTATUS) || !cm_HaveCallback(scp)) {
553         pCurrentEntry->TargetNameOffset = 0;
554         pCurrentEntry->TargetNameLength = 0;
555     }
556     else
557     switch (scp->fileType) {
558     case CM_SCACHETYPE_MOUNTPOINT:
559         if (dwFlags & RDR_POP_FOLLOW_MOUNTPOINTS) {
560             if ((code2 = cm_ReadMountPoint(scp, userp, reqp)) == 0) {
561                 cm_scache_t *targetScp = NULL;
562
563                 pCurrentEntry->TargetNameOffset = pCurrentEntry->FileNameOffset + pCurrentEntry->FileNameLength;
564                 len = strlen(scp->mountPointStringp);
565                 wtarget = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->TargetNameOffset);
566
567 #ifdef UNICODE
568                 cch = MultiByteToWideChar( CP_UTF8, 0, scp->mountPointStringp,
569                                            len * sizeof(char),
570                                            wtarget,
571                                            len * sizeof(WCHAR));
572 #else
573                 mbstowcs(wtarget, scp->mountPointStringp, len);
574 #endif
575                 pCurrentEntry->TargetNameLength = (ULONG)(sizeof(WCHAR) * len);
576
577                 code2 = cm_FollowMountPoint(scp, dscp, userp, reqp, &targetScp);
578
579                 if (code2 == 0) {
580                     pCurrentEntry->TargetFileId.Cell = targetScp->fid.cell;
581                     pCurrentEntry->TargetFileId.Volume = targetScp->fid.volume;
582                     pCurrentEntry->TargetFileId.Vnode = targetScp->fid.vnode;
583                     pCurrentEntry->TargetFileId.Unique = targetScp->fid.unique;
584                     pCurrentEntry->TargetFileId.Hash = targetScp->fid.hash;
585
586                     osi_Log4(afsd_logp, "RDR_PopulateCurrentEntry target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
587                               pCurrentEntry->TargetFileId.Cell, pCurrentEntry->TargetFileId.Volume,
588                               pCurrentEntry->TargetFileId.Vnode, pCurrentEntry->TargetFileId.Unique);
589
590                     cm_ReleaseSCache(targetScp);
591                 } else {
592                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_FollowMountPoint failed scp=0x%p code=0x%x",
593                               scp, code2);
594                 }
595             } else {
596                 osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_ReadMountPoint failed scp=0x%p code=0x%x",
597                           scp, code2);
598             }
599         }
600         break;
601     case CM_SCACHETYPE_SYMLINK:
602     case CM_SCACHETYPE_DFSLINK:
603         {
604             pCurrentEntry->TargetNameOffset = pCurrentEntry->FileNameOffset + pCurrentEntry->FileNameLength;
605             wtarget = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->TargetNameOffset);
606
607             if (dwFlags & RDR_POP_EVALUATE_SYMLINKS) {
608                 char * mp;
609
610                 code2 = cm_HandleLink(scp, userp, reqp);
611                 if (code2 == 0) {
612                     mp = scp->mountPointStringp;
613                     len = strlen(mp);
614                     if ( len != 0 ) {
615                         /* Strip off the msdfs: prefix from the target name for the file system */
616                         if (scp->fileType == CM_SCACHETYPE_DFSLINK) {
617                             osi_Log0(afsd_logp, "RDR_PopulateCurrentEntry DFSLink Detected");
618                             pCurrentEntry->FileType = scp->fileType;
619
620                             if (!strncmp("msdfs:", mp, 6)) {
621                                 mp += 6;
622                                 len -= 6;
623                             }
624                         }
625                         /* only send one slash to the redirector */
626                         if (mp[0] == '\\' && mp[1] == '\\') {
627                             mp++;
628                             len--;
629                         }
630 #ifdef UNICODE
631                         cch = MultiByteToWideChar( CP_UTF8, 0, mp,
632                                                    len * sizeof(char),
633                                                    wtarget,
634                                                    len * sizeof(WCHAR));
635 #else
636                         mbstowcs(wtarget, mp, len);
637 #endif
638                     }
639                     pCurrentEntry->TargetNameLength = (ULONG)(sizeof(WCHAR) * len);
640                 } else {
641                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_HandleLink failed scp=0x%p code=0x%x",
642                              scp, code2);
643                 }
644             }
645
646         }
647         break;
648
649     default:
650         pCurrentEntry->TargetNameOffset = 0;
651         pCurrentEntry->TargetNameLength = 0;
652     }
653     lock_ReleaseWrite(&scp->rw);
654
655     dwEntryLength += pCurrentEntry->FileNameLength + pCurrentEntry->TargetNameLength;
656     dwEntryLength += (dwEntryLength % 8) ? 8 - (dwEntryLength % 8) : 0;   /* quad align */
657     if (ppNextEntry)
658         *ppNextEntry = (AFSDirEnumEntry *)((PBYTE)pCurrentEntry + dwEntryLength);
659     if (pdwRemainingLength)
660         *pdwRemainingLength = dwMaxEntryLength - dwEntryLength;
661
662     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntry Success FileNameLength=%d TargetNameLength=%d RemainingLength=%d",
663               pCurrentEntry->FileNameLength, pCurrentEntry->TargetNameLength, *pdwRemainingLength);
664
665     return code;
666 }
667
668 static afs_uint32
669 RDR_PopulateCurrentEntryNoScp( IN  AFSDirEnumEntry * pCurrentEntry,
670                                IN  DWORD             dwMaxEntryLength,
671                                IN  cm_scache_t     * dscp,
672                                IN  cm_fid_t        * fidp,
673                                IN  cm_user_t       * userp,
674                                IN  cm_req_t        * reqp,
675                                IN  wchar_t         * name,
676                                IN  wchar_t         * shortName,
677                                IN  DWORD             dwFlags,
678                                IN  afs_uint32        cmError,
679                                OUT AFSDirEnumEntry **ppNextEntry,
680                                OUT DWORD           * pdwRemainingLength)
681 {
682     FILETIME ft;
683     WCHAR *  wname;
684     size_t   len;
685     DWORD      dwEntryLength;
686     afs_uint32 code = 0, code2 = 0;
687
688     osi_Log4(afsd_logp, "RDR_PopulateCurrentEntryNoEntry dscp=0x%p name=%S short=%S flags=0x%x",
689              dscp, osi_LogSaveStringW(afsd_logp, name),
690              osi_LogSaveStringW(afsd_logp, shortName), dwFlags);
691     osi_Log1(afsd_logp, "... maxLength=%d", dwMaxEntryLength);
692
693     if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
694         if (ppNextEntry)
695             *ppNextEntry = pCurrentEntry;
696         if (pdwRemainingLength)
697             *pdwRemainingLength = dwMaxEntryLength;
698         osi_Log2(afsd_logp, "RDR_PopulateCurrentEntryNoEntry Not Enough Room for Entry %d < %d",
699                  dwMaxEntryLength, sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t));
700         return CM_ERROR_TOOBIG;
701     }
702
703     if (!name)
704         name = L"";
705     if (!shortName)
706         shortName = L"";
707
708     dwEntryLength = sizeof(AFSDirEnumEntry);
709
710     /* Populate the error code */
711     smb_MapNTError(cmError, &pCurrentEntry->NTStatus, TRUE);
712
713     /* Populate the fake data */
714     pCurrentEntry->FileId.Cell = fidp->cell;
715     pCurrentEntry->FileId.Volume = fidp->volume;
716     pCurrentEntry->FileId.Vnode = fidp->vnode;
717     pCurrentEntry->FileId.Unique = fidp->unique;
718     pCurrentEntry->FileId.Hash = fidp->hash;
719
720     pCurrentEntry->FileType = CM_SCACHETYPE_UNKNOWN;
721
722     pCurrentEntry->DataVersion.QuadPart = CM_SCACHE_VERSION_BAD;
723
724     cm_LargeSearchTimeFromUnixTime(&ft, 0);
725     pCurrentEntry->Expiration.LowPart = ft.dwLowDateTime;
726     pCurrentEntry->Expiration.HighPart = ft.dwHighDateTime;
727
728     cm_LargeSearchTimeFromUnixTime(&ft, 0);
729     pCurrentEntry->CreationTime.LowPart = ft.dwLowDateTime;
730     pCurrentEntry->CreationTime.HighPart = ft.dwHighDateTime;
731     pCurrentEntry->LastAccessTime = pCurrentEntry->CreationTime;
732     pCurrentEntry->LastWriteTime = pCurrentEntry->CreationTime;
733     pCurrentEntry->ChangeTime = pCurrentEntry->CreationTime;
734
735     pCurrentEntry->EndOfFile.QuadPart = 0;
736     pCurrentEntry->AllocationSize.QuadPart = 0;
737     pCurrentEntry->FileAttributes = 0;
738     pCurrentEntry->EaSize = 0;
739     pCurrentEntry->Links = 0;
740
741     len = wcslen(shortName);
742     wcsncpy(pCurrentEntry->ShortName, shortName, len);
743     pCurrentEntry->ShortNameLength = (CCHAR)(len * sizeof(WCHAR));
744
745     pCurrentEntry->FileNameOffset = sizeof(AFSDirEnumEntry);
746     len = wcslen(name);
747     wname = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->FileNameOffset);
748     wcsncpy(wname, name, len);
749     pCurrentEntry->FileNameLength = (ULONG)(sizeof(WCHAR) * len);
750
751     pCurrentEntry->TargetNameOffset = 0;
752     pCurrentEntry->TargetNameLength = 0;
753
754     dwEntryLength += pCurrentEntry->FileNameLength + pCurrentEntry->TargetNameLength;
755     dwEntryLength += (dwEntryLength % 8) ? 8 - (dwEntryLength % 8) : 0;   /* quad align */
756     if (ppNextEntry)
757         *ppNextEntry = (AFSDirEnumEntry *)((PBYTE)pCurrentEntry + dwEntryLength);
758     if (pdwRemainingLength)
759         *pdwRemainingLength = dwMaxEntryLength - dwEntryLength;
760
761     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntryNoScp Success FileNameLength=%d TargetNameLength=%d RemainingLength=%d",
762               pCurrentEntry->FileNameLength, pCurrentEntry->TargetNameLength, *pdwRemainingLength);
763
764     return code;
765 }
766
767 void
768 RDR_EnumerateDirectory( IN cm_user_t *userp,
769                         IN AFSFileID DirID,
770                         IN AFSDirQueryCB *QueryCB,
771                         IN BOOL bWow64,
772                         IN BOOL bSkipStatus,
773                         IN DWORD ResultBufferLength,
774                         IN OUT AFSCommResult **ResultCB)
775 {
776     DWORD status;
777     cm_direnum_t *      enump = NULL;
778     AFSDirEnumResp  * pDirEnumResp;
779     AFSDirEnumEntry * pCurrentEntry;
780     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
781     DWORD             dwMaxEntryLength;
782     afs_uint32  code = 0;
783     cm_fid_t      fid;
784     cm_scache_t * dscp = NULL;
785     cm_req_t      req;
786
787     RDR_InitReq(&req, bWow64);
788
789     osi_Log4(afsd_logp, "RDR_EnumerateDirectory FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
790              DirID.Cell, DirID.Volume, DirID.Vnode, DirID.Unique);
791
792     *ResultCB = (AFSCommResult *)malloc(size);
793     if (!(*ResultCB)) {
794         osi_Log0(afsd_logp, "RDR_EnumerateDirectory Out of Memory");
795         return;
796     }
797
798     memset(*ResultCB, 0, size);
799
800     if (QueryCB->EnumHandle == (ULONG_PTR)-1) {
801         osi_Log0(afsd_logp, "RDR_EnumerateDirectory No More Entries");
802         (*ResultCB)->ResultStatus = STATUS_NO_MORE_ENTRIES;
803         (*ResultCB)->ResultBufferLength = 0;
804         return;
805     }
806
807     (*ResultCB)->ResultBufferLength = dwMaxEntryLength = ResultBufferLength;
808     if (ResultBufferLength) {
809         pDirEnumResp = (AFSDirEnumResp *)&(*ResultCB)->ResultData;
810         pCurrentEntry = (AFSDirEnumEntry *)&pDirEnumResp->Entry;
811         dwMaxEntryLength -= FIELD_OFFSET( AFSDirEnumResp, Entry);      /* AFSDirEnumResp */
812     }
813
814     if (DirID.Cell != 0) {
815         fid.cell   = DirID.Cell;
816         fid.volume = DirID.Volume;
817         fid.vnode  = DirID.Vnode;
818         fid.unique = DirID.Unique;
819         fid.hash   = DirID.Hash;
820
821         code = cm_GetSCache(&fid, NULL, &dscp, userp, &req);
822         if (code) {
823             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
824             (*ResultCB)->ResultStatus = status;
825             osi_Log2(afsd_logp, "RDR_EnumerateDirectory cm_GetSCache failure code=0x%x status=0x%x",
826                       code, status);
827             return;
828         }
829     } else {
830         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
831         osi_Log0(afsd_logp, "RDR_EnumerateDirectory Object Name Invalid - Cell = 0");
832         return;
833     }
834
835     /* get the directory size */
836     lock_ObtainWrite(&dscp->rw);
837     code = cm_SyncOp(dscp, NULL, userp, &req, PRSFS_LOOKUP,
838                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
839     if (code) {
840         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
841         (*ResultCB)->ResultStatus = status;
842         lock_ReleaseWrite(&dscp->rw);
843         cm_ReleaseSCache(dscp);
844         osi_Log2(afsd_logp, "RDR_EnumerateDirectory cm_SyncOp failure code=0x%x status=0x%x",
845                   code, status);
846         return;
847     }
848
849     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
850     lock_ReleaseWrite(&dscp->rw);
851
852     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
853         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
854         cm_ReleaseSCache(dscp);
855         osi_Log1(afsd_logp, "RDR_EnumerateDirectory Not a Directory dscp=0x%p",
856                  dscp);
857         return;
858     }
859
860     osi_Log1(afsd_logp, "RDR_EnumerateDirectory dv=%u", (afs_uint32)dscp->dataVersion);
861
862     /*
863      * If there is no enumeration handle, then this is a new query
864      * and we must perform an enumeration for the specified object.
865      */
866     if (QueryCB->EnumHandle == (ULONG_PTR)NULL) {
867         cm_dirOp_t    dirop;
868
869         code = cm_BeginDirOp(dscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
870         if (code == 0) {
871             code = cm_BPlusDirEnumerate(dscp, userp, &req,
872                                         TRUE /* dir locked */, NULL /* no mask */,
873                                         TRUE /* fetch status? */, &enump);
874             if (code) {
875                 osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BPlusDirEnumerate failure code=0x%x",
876                           code);
877             }
878             cm_EndDirOp(&dirop);
879         } else {
880             osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BeginDirOp failure code=0x%x",
881                       code);
882         }
883     } else {
884         enump = (cm_direnum_t *)QueryCB->EnumHandle;
885     }
886
887     if (enump) {
888         if (ResultBufferLength == 0) {
889             code = cm_BPlusDirEnumBulkStat(enump);
890             if (code) {
891                 osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BPlusDirEnumBulkStat failure code=0x%x",
892                           code);
893             }
894         } else {
895             cm_direnum_entry_t * entryp = NULL;
896
897             pDirEnumResp->SnapshotDataVersion.QuadPart = enump->dataVersion;
898
899           getnextentry:
900             if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
901                 osi_Log0(afsd_logp, "RDR_EnumerateDirectory out of space, returning");
902                 goto outofspace;
903             }
904
905             code = cm_BPlusDirNextEnumEntry(enump, &entryp);
906
907             if ((code == 0 || code == CM_ERROR_STOPNOW) && entryp) {
908                 cm_scache_t *scp = NULL;
909                 int stopnow = (code == CM_ERROR_STOPNOW);
910
911                 if ( !wcscmp(L".", entryp->name) || !wcscmp(L"..", entryp->name) ) {
912                     osi_Log0(afsd_logp, "RDR_EnumerateDirectory skipping . or ..");
913                     if (stopnow)
914                         goto outofspace;
915                     goto getnextentry;
916                 }
917
918                 if (bSkipStatus) {
919                     code = cm_GetSCache(&entryp->fid, &dscp->fid, &scp, userp, &req);
920                     if (code) {
921                         osi_Log5(afsd_logp, "RDR_EnumerateDirectory cm_GetSCache failure cell %u vol %u vnode %u uniq %u code=0x%x",
922                                  entryp->fid.cell, entryp->fid.volume, entryp->fid.vnode, entryp->fid.unique, code);
923                     }
924                 } else {
925                     code = entryp->errorCode;
926                     scp = code ? NULL : cm_FindSCache(&entryp->fid);
927                 }
928
929                 if (scp) {
930                     code = RDR_PopulateCurrentEntry( pCurrentEntry, dwMaxEntryLength,
931                                                      dscp, scp, userp, &req,
932                                                      entryp->name,
933                                                      cm_shortNames && cm_Is8Dot3(entryp->name) ? NULL : entryp->shortName,
934                                                      (bWow64 ? RDR_POP_WOW64 : 0) |
935                                                      (bSkipStatus ? RDR_POP_NO_GETSTATUS : 0),
936                                                      code,
937                                                      &pCurrentEntry, &dwMaxEntryLength);
938                     cm_ReleaseSCache(scp);
939                 } else {
940                     code = RDR_PopulateCurrentEntryNoScp( pCurrentEntry, dwMaxEntryLength,
941                                                           dscp, &entryp->fid, userp, &req,
942                                                           entryp->name,
943                                                           cm_shortNames && cm_Is8Dot3(entryp->name) ? NULL : entryp->shortName,
944                                                           (bWow64 ? RDR_POP_WOW64 : 0),
945                                                           code,
946                                                           &pCurrentEntry, &dwMaxEntryLength);
947                 }
948                 if (stopnow)
949                     goto outofspace;
950                 goto getnextentry;
951             }
952         }
953     }
954
955   outofspace:
956
957     if (code || enump->next == enump->count || ResultBufferLength == 0) {
958         cm_BPlusDirFreeEnumeration(enump);
959         enump = (cm_direnum_t *)(ULONG_PTR)-1;
960     }
961
962     if (code == 0 || code == CM_ERROR_STOPNOW) {
963         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
964         osi_Log0(afsd_logp, "RDR_EnumerateDirectory SUCCESS");
965     } else {
966         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
967         (*ResultCB)->ResultStatus = status;
968         osi_Log2(afsd_logp, "RDR_EnumerateDirectory Failure code=0x%x status=0x%x",
969                   code, status);
970     }
971
972     if (ResultBufferLength) {
973         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwMaxEntryLength;
974
975         pDirEnumResp->EnumHandle = (ULONG_PTR) enump;
976         pDirEnumResp->CurrentDataVersion.QuadPart = dscp->dataVersion;
977     }
978
979     if (dscp)
980         cm_ReleaseSCache(dscp);
981
982     return;
983 }
984
985 void
986 RDR_EvaluateNodeByName( IN cm_user_t *userp,
987                         IN AFSFileID ParentID,
988                         IN WCHAR   *FileNameCounted,
989                         IN DWORD    FileNameLength,
990                         IN BOOL     CaseSensitive,
991                         IN BOOL     bWow64,
992                         IN BOOL     bHoldFid,
993                         IN BOOL     bNoFollow,
994                         IN DWORD    ResultBufferLength,
995                         IN OUT AFSCommResult **ResultCB)
996 {
997     AFSFileEvalResultCB *pEvalResultCB = NULL;
998     AFSDirEnumEntry * pCurrentEntry;
999     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
1000     afs_uint32  code = 0;
1001     cm_scache_t * scp = NULL;
1002     cm_scache_t * dscp = NULL;
1003     cm_req_t      req;
1004     cm_fid_t      parentFid;
1005     DWORD         status;
1006     DWORD         dwRemaining;
1007     WCHAR       * wszName = NULL;
1008     size_t        cbName;
1009     BOOL          bVol = FALSE;
1010     wchar_t       FileName[260];
1011
1012     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1013
1014     RDR_InitReq(&req, bWow64);
1015
1016     osi_Log4(afsd_logp, "RDR_EvaluateNodeByName parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1017              ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1018
1019     /* Allocate enough room to add a volume prefix if necessary */
1020     cbName = FileNameLength + (CM_PREFIX_VOL_CCH + 64) * sizeof(WCHAR);
1021     wszName = malloc(cbName);
1022     if (!wszName) {
1023         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Out of Memory");
1024         return;
1025     }
1026     StringCbCopyNW(wszName, cbName, FileName, FileNameLength);
1027     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, wszName));
1028
1029     *ResultCB = (AFSCommResult *)malloc(size);
1030     if (!(*ResultCB)) {
1031         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Out of Memory");
1032         free(wszName);
1033         return;
1034     }
1035
1036     memset(*ResultCB, 0, size);
1037     (*ResultCB)->ResultBufferLength = 0;
1038     dwRemaining = ResultBufferLength;
1039     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1040         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1041         pCurrentEntry = &pEvalResultCB->DirEnum;
1042         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1043     }
1044
1045     if (ParentID.Cell != 0) {
1046         parentFid.cell   = ParentID.Cell;
1047         parentFid.volume = ParentID.Volume;
1048         parentFid.vnode  = ParentID.Vnode;
1049         parentFid.unique = ParentID.Unique;
1050         parentFid.hash   = ParentID.Hash;
1051
1052         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1053         if (code) {
1054             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1055             (*ResultCB)->ResultStatus = status;
1056             if ( status == STATUS_INVALID_HANDLE)
1057                 status = STATUS_OBJECT_PATH_INVALID;
1058             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName cm_GetSCache parentFID failure code=0x%x status=0x%x",
1059                       code, status);
1060             free(wszName);
1061             return;
1062         }
1063     } else {
1064         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1065         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Object Name Invalid - Cell = 0");
1066         return;
1067     }
1068
1069     /* get the directory size */
1070     lock_ObtainWrite(&dscp->rw);
1071     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1072                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1073     if (code) {
1074         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1075         (*ResultCB)->ResultStatus = status;
1076         lock_ReleaseWrite(&dscp->rw);
1077         cm_ReleaseSCache(dscp);
1078         osi_Log3(afsd_logp, "RDR_EvaluateNodeByName cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1079                  dscp, code, status);
1080         free(wszName);
1081         return;
1082     }
1083     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1084     lock_ReleaseWrite(&dscp->rw);
1085
1086     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1087         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1088         cm_ReleaseSCache(dscp);
1089         osi_Log1(afsd_logp, "RDR_EvaluateNodeByName Not a Directory dscp=0x%p",
1090                  dscp);
1091         free(wszName);
1092         return;
1093     }
1094
1095     code = cm_Lookup(dscp, wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1096
1097     if ((code == CM_ERROR_NOSUCHPATH || code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) &&
1098          dscp == cm_data.rootSCachep) {
1099
1100         if (wcschr(wszName, '%') != NULL || wcschr(wszName, '#') != NULL) {
1101             /*
1102              * A volume reference:  <cell>{%,#}<volume> -> @vol:<cell>{%,#}<volume>
1103              */
1104             StringCchCopyNW(wszName, cbName, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH);
1105             StringCbCatNW(wszName, cbName, FileName, FileNameLength);
1106             bVol = TRUE;
1107
1108             code = cm_EvaluateVolumeReference(wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1109         }
1110 #ifdef AFS_FREELANCE_CLIENT
1111         else if (dscp->fid.cell == AFS_FAKE_ROOT_CELL_ID && dscp->fid.volume == AFS_FAKE_ROOT_VOL_ID &&
1112                  dscp->fid.vnode == 1 && dscp->fid.unique == 1) {
1113             /*
1114              * If this is the Freelance volume root directory then treat unrecognized
1115              * names as cell names and attempt to find the appropriate "root.cell".
1116              */
1117             StringCchCopyNW(wszName, cbName, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH);
1118             if (FileName[0] == L'.') {
1119                 StringCbCatNW(wszName, cbName, &FileName[1], FileNameLength);
1120                 StringCbCatNW(wszName, cbName, L"%", sizeof(WCHAR));
1121             } else {
1122                 StringCbCatNW(wszName, cbName, FileName, FileNameLength);
1123                 StringCbCatNW(wszName, cbName, L"#", sizeof(WCHAR));
1124             }
1125             StringCbCatNW(wszName, cbName, L"root.cell", 9 * sizeof(WCHAR));
1126             bVol = TRUE;
1127
1128             code = cm_EvaluateVolumeReference(wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1129         }
1130 #endif
1131     }
1132
1133     if (code == 0 && scp) {
1134         wchar_t shortName[13]=L"";
1135
1136         if (!cm_shortNames) {
1137             shortName[0] = L'\0';
1138         } else if (bVol) {
1139             cm_Gen8Dot3VolNameW(scp->fid.cell, scp->fid.volume, shortName, NULL);
1140         } else if (!cm_Is8Dot3(wszName)) {
1141             cm_dirFid_t dfid;
1142
1143             dfid.vnode = htonl(scp->fid.vnode);
1144             dfid.unique = htonl(scp->fid.unique);
1145
1146             cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1147         } else {
1148             shortName[0] = L'\0';
1149         }
1150
1151         code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1152                                         dscp, scp, userp, &req,
1153                                         FileName, shortName,
1154                                         (bWow64 ? RDR_POP_WOW64 : 0) |
1155                                         (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1156                                         0, NULL, &dwRemaining);
1157         if (bHoldFid)
1158             RDR_FlagScpInUse( scp, FALSE );
1159         cm_ReleaseSCache(scp);
1160
1161         if (code) {
1162             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1163             (*ResultCB)->ResultStatus = status;
1164             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1165                       code, status);
1166         } else {
1167             pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1168             (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1169             (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1170             osi_Log0(afsd_logp, "RDR_EvaluateNodeByName SUCCESS");
1171         }
1172     } else if (code) {
1173         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1174         (*ResultCB)->ResultStatus = status;
1175         osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1176                  code, status);
1177     } else {
1178         (*ResultCB)->ResultStatus = STATUS_NO_SUCH_FILE;
1179         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName No Such File");
1180     }
1181     cm_ReleaseSCache(dscp);
1182     free(wszName);
1183
1184     return;
1185 }
1186
1187 void
1188 RDR_EvaluateNodeByID( IN cm_user_t *userp,
1189                       IN AFSFileID ParentID,            /* not used */
1190                       IN AFSFileID SourceID,
1191                       IN BOOL      bWow64,
1192                       IN BOOL      bNoFollow,
1193                       IN BOOL      bHoldFid,
1194                       IN DWORD     ResultBufferLength,
1195                       IN OUT AFSCommResult **ResultCB)
1196 {
1197     AFSFileEvalResultCB *pEvalResultCB = NULL;
1198     AFSDirEnumEntry * pCurrentEntry = NULL;
1199     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
1200     afs_uint32  code = 0;
1201     cm_scache_t * scp = NULL;
1202     cm_scache_t * dscp = NULL;
1203     cm_req_t      req;
1204     cm_fid_t      Fid;
1205     cm_fid_t      parentFid;
1206     DWORD         status;
1207     DWORD         dwRemaining;
1208
1209     osi_Log4(afsd_logp, "RDR_EvaluateNodeByID source FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1210               SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1211     osi_Log4(afsd_logp, "... parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1212               ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1213
1214     *ResultCB = (AFSCommResult *)malloc(size);
1215     if (!(*ResultCB)) {
1216         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Out of Memory");
1217         return;
1218     }
1219
1220     memset(*ResultCB, 0, size);
1221     (*ResultCB)->ResultBufferLength = 0;
1222     dwRemaining = ResultBufferLength;
1223     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1224         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1225         pCurrentEntry = &pEvalResultCB->DirEnum;
1226         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1227     }
1228
1229     RDR_InitReq(&req, bWow64);
1230
1231     if (SourceID.Cell != 0) {
1232         cm_SetFid(&Fid, SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1233         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
1234         if (code) {
1235             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1236             (*ResultCB)->ResultStatus = status;
1237             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache SourceFID failure code=0x%x status=0x%x",
1238                       code, status);
1239             return;
1240         }
1241     } else {
1242         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1243         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Name Invalid - Cell = 0");
1244         return;
1245     }
1246
1247     if (ParentID.Cell != 0) {
1248         cm_SetFid(&parentFid, ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1249         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1250         if (code) {
1251             cm_ReleaseSCache(scp);
1252             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1253             if ( status == STATUS_INVALID_HANDLE)
1254                 status = STATUS_OBJECT_PATH_INVALID;
1255             (*ResultCB)->ResultStatus = status;
1256             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1257                       code, status);
1258             return;
1259         }
1260     } else if (SourceID.Vnode == 1) {
1261         dscp = scp;
1262         cm_HoldSCache(dscp);
1263     } else if (scp->parentVnode) {
1264         cm_SetFid(&parentFid, SourceID.Cell, SourceID.Volume, scp->parentVnode, scp->parentUnique);
1265         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1266         if (code) {
1267             cm_ReleaseSCache(scp);
1268             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1269             if ( status == STATUS_INVALID_HANDLE)
1270                 status = STATUS_OBJECT_PATH_INVALID;
1271             (*ResultCB)->ResultStatus = status;
1272             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1273                       code, status);
1274             return;
1275         }
1276     } else {
1277         (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
1278         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Path Invalid - Unknown Parent");
1279         return;
1280     }
1281
1282     /* Make sure the directory is current */
1283     lock_ObtainWrite(&dscp->rw);
1284     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1285                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1286     if (code) {
1287         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1288         (*ResultCB)->ResultStatus = status;
1289         lock_ReleaseWrite(&dscp->rw);
1290         cm_ReleaseSCache(dscp);
1291         cm_ReleaseSCache(scp);
1292         osi_Log3(afsd_logp, "RDR_EvaluateNodeByID cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1293                  dscp, code, status);
1294         return;
1295     }
1296
1297     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1298     lock_ReleaseWrite(&dscp->rw);
1299
1300     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1301         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1302         cm_ReleaseSCache(dscp);
1303         cm_ReleaseSCache(scp);
1304         osi_Log1(afsd_logp, "RDR_EvaluateNodeByID Not a Directory dscp=0x%p", dscp);
1305         return;
1306     }
1307
1308     code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1309                                     dscp, scp, userp, &req, NULL, NULL,
1310                                     (bWow64 ? RDR_POP_WOW64 : 0) |
1311                                     (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1312                                     0, NULL, &dwRemaining);
1313
1314     if (bHoldFid)
1315         RDR_FlagScpInUse( scp, FALSE );
1316     cm_ReleaseSCache(scp);
1317     cm_ReleaseSCache(dscp);
1318
1319     if (code) {
1320         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1321         (*ResultCB)->ResultStatus = status;
1322         osi_Log2(afsd_logp, "RDR_EvaluateNodeByID FAILURE code=0x%x status=0x%x",
1323                  code, status);
1324     } else {
1325         pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1326
1327         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1328         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1329         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID SUCCESS");
1330     }
1331     return;
1332 }
1333
1334 void
1335 RDR_CreateFileEntry( IN cm_user_t *userp,
1336                      IN WCHAR *FileNameCounted,
1337                      IN DWORD FileNameLength,
1338                      IN AFSFileCreateCB *CreateCB,
1339                      IN BOOL bWow64,
1340                      IN BOOL bHoldFid,
1341                      IN DWORD ResultBufferLength,
1342                      IN OUT AFSCommResult **ResultCB)
1343 {
1344     AFSFileCreateResultCB *pResultCB = NULL;
1345     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1346     cm_fid_t            parentFid;
1347     afs_uint32          code;
1348     cm_scache_t *       dscp = NULL;
1349     afs_uint32          flags = 0;
1350     cm_attr_t           setAttr;
1351     cm_scache_t *       scp = NULL;
1352     cm_req_t            req;
1353     DWORD               status;
1354     wchar_t             FileName[260];
1355
1356     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1357
1358     osi_Log4(afsd_logp, "RDR_CreateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1359               CreateCB->ParentId.Cell, CreateCB->ParentId.Volume,
1360               CreateCB->ParentId.Vnode, CreateCB->ParentId.Unique);
1361     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, FileName));
1362
1363     RDR_InitReq(&req, bWow64);
1364     memset(&setAttr, 0, sizeof(cm_attr_t));
1365
1366     *ResultCB = (AFSCommResult *)malloc(size);
1367     if (!(*ResultCB)) {
1368         osi_Log0(afsd_logp, "RDR_CreateFileEntry out of memory");
1369         return;
1370     }
1371
1372     memset( *ResultCB,
1373             '\0',
1374             size);
1375
1376     parentFid.cell   = CreateCB->ParentId.Cell;
1377     parentFid.volume = CreateCB->ParentId.Volume;
1378     parentFid.vnode  = CreateCB->ParentId.Vnode;
1379     parentFid.unique = CreateCB->ParentId.Unique;
1380     parentFid.hash   = CreateCB->ParentId.Hash;
1381
1382     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1383     if (code) {
1384         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1385         (*ResultCB)->ResultStatus = status;
1386         if ( status == STATUS_INVALID_HANDLE)
1387             status = STATUS_OBJECT_PATH_INVALID;
1388         osi_Log2(afsd_logp, "RDR_CreateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1389                   code, status);
1390         return;
1391     }
1392
1393     lock_ObtainWrite(&dscp->rw);
1394     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1395                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1396     if (code) {
1397         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1398         (*ResultCB)->ResultStatus = status;
1399         lock_ReleaseWrite(&dscp->rw);
1400         cm_ReleaseSCache(dscp);
1401         osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (1) dscp=0x%p code=0x%x status=0x%x",
1402                  dscp, code, status);
1403         return;
1404     }
1405
1406     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1407     lock_ReleaseWrite(&dscp->rw);
1408
1409     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1410         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1411         cm_ReleaseSCache(dscp);
1412         osi_Log1(afsd_logp, "RDR_CreateFileEntry Not a Directory dscp=0x%p",
1413                  dscp);
1414         return;
1415     }
1416
1417     /* Use current time */
1418     setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
1419     setAttr.clientModTime = time(NULL);
1420
1421     if (CreateCB->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1422         if (smb_unixModeDefaultDir) {
1423             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1424             setAttr.unixModeBits = smb_unixModeDefaultDir;
1425             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1426                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1427         }
1428
1429         code = cm_MakeDir(dscp, FileName, flags, &setAttr, userp, &req, &scp);
1430     } else {
1431         if (smb_unixModeDefaultFile) {
1432             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1433             setAttr.unixModeBits = smb_unixModeDefaultFile;
1434             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1435                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1436         }
1437
1438         setAttr.mask |= CM_ATTRMASK_LENGTH;
1439         setAttr.length.LowPart = CreateCB->AllocationSize.LowPart;
1440         setAttr.length.HighPart = CreateCB->AllocationSize.HighPart;
1441         code = cm_Create(dscp, FileName, flags, &setAttr, &scp, userp, &req);
1442     }
1443     if (code == 0) {
1444         wchar_t shortName[13]=L"";
1445         cm_dirFid_t dfid;
1446         DWORD dwRemaining;
1447
1448         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
1449
1450         (*ResultCB)->ResultBufferLength = sizeof( AFSFileCreateResultCB);
1451
1452         pResultCB = (AFSFileCreateResultCB *)(*ResultCB)->ResultData;
1453
1454         dwRemaining = ResultBufferLength - sizeof( AFSFileCreateResultCB) + sizeof( AFSDirEnumEntry);
1455
1456         lock_ObtainWrite(&dscp->rw);
1457         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1458                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1459         if (code) {
1460             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1461             (*ResultCB)->ResultStatus = status;
1462             lock_ReleaseWrite(&dscp->rw);
1463             cm_ReleaseSCache(dscp);
1464             cm_ReleaseSCache(scp);
1465             osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (2) dscp=0x%p code=0x%x status=0x%x",
1466                       dscp, code, status);
1467             return;
1468         }
1469
1470         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1471
1472         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1473         lock_ReleaseWrite(&dscp->rw);
1474
1475         if (cm_shortNames) {
1476             dfid.vnode = htonl(scp->fid.vnode);
1477             dfid.unique = htonl(scp->fid.unique);
1478
1479             if (!cm_Is8Dot3(FileName))
1480                 cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1481             else
1482                 shortName[0] = '\0';
1483         }
1484
1485         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1486                                         dscp, scp, userp, &req, FileName, shortName,
1487                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1488                                         0, NULL, &dwRemaining);
1489
1490         if (bHoldFid)
1491             RDR_FlagScpInUse( scp, FALSE );
1492         cm_ReleaseSCache(scp);
1493         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1494         osi_Log0(afsd_logp, "RDR_CreateFileEntry SUCCESS");
1495     } else {
1496         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1497         (*ResultCB)->ResultStatus = status;
1498         (*ResultCB)->ResultBufferLength = 0;
1499         osi_Log2(afsd_logp, "RDR_CreateFileEntry FAILURE code=0x%x status=0x%x",
1500                   code, status);
1501     }
1502
1503     cm_ReleaseSCache(dscp);
1504
1505     return;
1506 }
1507
1508 void
1509 RDR_UpdateFileEntry( IN cm_user_t *userp,
1510                      IN AFSFileID FileId,
1511                      IN AFSFileUpdateCB *UpdateCB,
1512                      IN BOOL bWow64,
1513                      IN DWORD ResultBufferLength,
1514                      IN OUT AFSCommResult **ResultCB)
1515 {
1516     AFSFileUpdateResultCB *pResultCB = NULL;
1517     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1518     cm_fid_t            Fid;
1519     cm_fid_t            parentFid;
1520     afs_uint32          code;
1521     afs_uint32          flags = 0;
1522     cm_attr_t           setAttr;
1523     cm_scache_t *       scp = NULL;
1524     cm_scache_t *       dscp = NULL;
1525     cm_req_t            req;
1526     time_t              clientModTime;
1527     FILETIME            ft;
1528     DWORD               status;
1529     BOOL                bScpLocked = FALSE;
1530
1531     RDR_InitReq(&req, bWow64);
1532     memset(&setAttr, 0, sizeof(cm_attr_t));
1533
1534     osi_Log4(afsd_logp, "RDR_UpdateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1535               UpdateCB->ParentId.Cell, UpdateCB->ParentId.Volume,
1536               UpdateCB->ParentId.Vnode, UpdateCB->ParentId.Unique);
1537     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1538               FileId.Cell, FileId.Volume,
1539               FileId.Vnode, FileId.Unique);
1540
1541     *ResultCB = (AFSCommResult *)malloc( size);
1542     if (!(*ResultCB)) {
1543         osi_Log0(afsd_logp, "RDR_UpdateFileEntry Out of Memory");
1544         return;
1545     }
1546
1547     memset( *ResultCB,
1548             '\0',
1549             size);
1550
1551     parentFid.cell   = UpdateCB->ParentId.Cell;
1552     parentFid.volume = UpdateCB->ParentId.Volume;
1553     parentFid.vnode  = UpdateCB->ParentId.Vnode;
1554     parentFid.unique = UpdateCB->ParentId.Unique;
1555     parentFid.hash   = UpdateCB->ParentId.Hash;
1556
1557     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1558     if (code) {
1559         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1560         (*ResultCB)->ResultStatus = status;
1561         if ( status == STATUS_INVALID_HANDLE)
1562             status = STATUS_OBJECT_PATH_INVALID;
1563         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1564                   code, status);
1565         return;
1566     }
1567
1568     lock_ObtainWrite(&dscp->rw);
1569     bScpLocked = TRUE;
1570     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1571                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1572     if (code) {
1573         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1574         (*ResultCB)->ResultStatus = status;
1575         lock_ReleaseWrite(&dscp->rw);
1576         cm_ReleaseSCache(dscp);
1577         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1578                  dscp, code, status);
1579         return;
1580     }
1581
1582     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1583     lock_ReleaseWrite(&dscp->rw);
1584     bScpLocked = FALSE;
1585
1586     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1587         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1588         cm_ReleaseSCache(dscp);
1589         osi_Log1(afsd_logp, "RDR_UpdateFileEntry Not a Directory dscp=0x%p",
1590                  dscp);
1591         return;
1592     }
1593
1594     Fid.cell   = FileId.Cell;
1595     Fid.volume = FileId.Volume;
1596     Fid.vnode  = FileId.Vnode;
1597     Fid.unique = FileId.Unique;
1598     Fid.hash   = FileId.Hash;
1599
1600     code = cm_GetSCache(&Fid, &dscp->fid, &scp, userp, &req);
1601     if (code) {
1602         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1603         (*ResultCB)->ResultStatus = status;
1604         cm_ReleaseSCache(dscp);
1605         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache object FID failure code=0x%x status=0x%x",
1606                   code, status);
1607         return;
1608     }
1609
1610     lock_ObtainWrite(&scp->rw);
1611     bScpLocked = TRUE;
1612     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1613                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1614     if (code) {
1615         lock_ReleaseWrite(&scp->rw);
1616         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1617         (*ResultCB)->ResultStatus = status;
1618         (*ResultCB)->ResultBufferLength = 0;
1619         cm_ReleaseSCache(dscp);
1620         cm_ReleaseSCache(scp);
1621         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
1622                  scp, code, status);
1623         return;
1624     }
1625     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1626
1627     if (UpdateCB->ChangeTime.QuadPart) {
1628
1629         if (scp->fileType == CM_SCACHETYPE_FILE) {
1630             /* Do not set length and other attributes at the same time */
1631             if (scp->length.QuadPart != UpdateCB->AllocationSize.QuadPart) {
1632                 osi_Log2(afsd_logp, "RDR_UpdateFileEntry Length Change 0x%x -> 0x%x",
1633                           (afs_uint32)scp->length.QuadPart, (afs_uint32)UpdateCB->AllocationSize.QuadPart);
1634                 setAttr.mask |= CM_ATTRMASK_LENGTH;
1635                 setAttr.length.LowPart = UpdateCB->AllocationSize.LowPart;
1636                 setAttr.length.HighPart = UpdateCB->AllocationSize.HighPart;
1637                 lock_ReleaseWrite(&scp->rw);
1638                 bScpLocked = FALSE;
1639                 code = cm_SetAttr(scp, &setAttr, userp, &req);
1640                 if (code)
1641                     goto on_error;
1642                 setAttr.mask = 0;
1643             }
1644         }
1645
1646         if (!bScpLocked) {
1647             lock_ObtainWrite(&scp->rw);
1648             bScpLocked = TRUE;
1649         }
1650         if ((scp->unixModeBits & 0200) && (UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1651             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1652             setAttr.unixModeBits = scp->unixModeBits & ~0222;
1653         } else if (!(scp->unixModeBits & 0200) && !(UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1654             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1655             setAttr.unixModeBits = scp->unixModeBits | 0222;
1656         }
1657     }
1658
1659     if (UpdateCB->LastWriteTime.QuadPart) {
1660         ft.dwLowDateTime = UpdateCB->LastWriteTime.LowPart;
1661         ft.dwHighDateTime = UpdateCB->LastWriteTime.HighPart;
1662
1663         cm_UnixTimeFromLargeSearchTime(& clientModTime, &ft);
1664
1665         if (!bScpLocked) {
1666             lock_ObtainWrite(&scp->rw);
1667             bScpLocked = TRUE;
1668         }
1669         if (scp->clientModTime != clientModTime) {
1670             setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1671             setAttr.clientModTime = clientModTime;
1672         }
1673
1674         /* call setattr */
1675         if (setAttr.mask) {
1676             lock_ReleaseWrite(&scp->rw);
1677             bScpLocked = FALSE;
1678             code = cm_SetAttr(scp, &setAttr, userp, &req);
1679         } else
1680             code = 0;
1681     }
1682
1683   on_error:
1684     if (bScpLocked) {
1685         lock_ReleaseWrite(&scp->rw);
1686     }
1687
1688     if (code == 0) {
1689         DWORD dwRemaining = ResultBufferLength - sizeof( AFSFileUpdateResultCB) + sizeof( AFSDirEnumEntry);
1690
1691         pResultCB = (AFSFileUpdateResultCB *)(*ResultCB)->ResultData;
1692
1693         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1694
1695         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1696                                         dscp, scp, userp, &req, NULL, NULL,
1697                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1698                                         0, NULL, &dwRemaining);
1699         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1700         osi_Log0(afsd_logp, "RDR_UpdateFileEntry SUCCESS");
1701     } else {
1702         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1703         (*ResultCB)->ResultStatus = status;
1704         (*ResultCB)->ResultBufferLength = 0;
1705         osi_Log2(afsd_logp, "RDR_UpdateFileEntry FAILURE code=0x%x status=0x%x",
1706                   code, status);
1707     }
1708     cm_ReleaseSCache(scp);
1709     cm_ReleaseSCache(dscp);
1710
1711     return;
1712 }
1713
1714 void
1715 RDR_CleanupFileEntry( IN cm_user_t *userp,
1716                       IN AFSFileID FileId,
1717                       IN WCHAR *FileNameCounted,
1718                       IN DWORD FileNameLength,
1719                       IN AFSFileCleanupCB *CleanupCB,
1720                       IN BOOL bWow64,
1721                       IN BOOL bLastHandle,
1722                       IN BOOL bDeleteFile,
1723                       IN BOOL bUnlockFile,
1724                       IN DWORD ResultBufferLength,
1725                       IN OUT AFSCommResult **ResultCB)
1726 {
1727     AFSFileCleanupResultCB *pResultCB = NULL;
1728     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1729     cm_fid_t            Fid;
1730     cm_fid_t            parentFid;
1731     afs_uint32          code = 0;
1732     afs_uint32          flags = 0;
1733     cm_attr_t           setAttr;
1734     cm_scache_t *       scp = NULL;
1735     cm_scache_t *       dscp = NULL;
1736     cm_req_t            req;
1737     time_t              clientModTime;
1738     FILETIME            ft;
1739     DWORD               status;
1740     BOOL                bScpLocked = FALSE;
1741     BOOL                bDscpLocked = FALSE;
1742     BOOL                bFlushFile = FALSE;
1743     cm_key_t            key;
1744
1745     RDR_InitReq(&req, bWow64);
1746     memset(&setAttr, 0, sizeof(cm_attr_t));
1747
1748     osi_Log4(afsd_logp, "RDR_CleanupFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1749               CleanupCB->ParentId.Cell, CleanupCB->ParentId.Volume,
1750               CleanupCB->ParentId.Vnode, CleanupCB->ParentId.Unique);
1751     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1752               FileId.Cell, FileId.Volume,
1753               FileId.Vnode, FileId.Unique);
1754
1755     *ResultCB = (AFSCommResult *)malloc( size);
1756     if (!(*ResultCB)) {
1757         osi_Log0(afsd_logp, "RDR_CleanupFileEntry Out of Memory");
1758         return;
1759     }
1760
1761     memset( *ResultCB,
1762             '\0',
1763             size);
1764
1765     parentFid.cell   = CleanupCB->ParentId.Cell;
1766     parentFid.volume = CleanupCB->ParentId.Volume;
1767     parentFid.vnode  = CleanupCB->ParentId.Vnode;
1768     parentFid.unique = CleanupCB->ParentId.Unique;
1769     parentFid.hash   = CleanupCB->ParentId.Hash;
1770
1771     if (parentFid.cell) {
1772         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1773         if (code) {
1774             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1775             if ( status == STATUS_INVALID_HANDLE)
1776                 status = STATUS_OBJECT_PATH_INVALID;
1777             (*ResultCB)->ResultStatus = status;
1778             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1779                      code, status);
1780             return;
1781         }
1782
1783         lock_ObtainWrite(&dscp->rw);
1784         bDscpLocked = TRUE;
1785         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1786                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1787         if (code) {
1788             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure dscp=0x%p code=0x%x",
1789                     dscp, code);
1790             if (code)
1791                 goto on_error;
1792         }
1793
1794         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1795         lock_ReleaseWrite(&dscp->rw);
1796         bDscpLocked = FALSE;
1797
1798         if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1799             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1800             cm_ReleaseSCache(dscp);
1801             osi_Log1(afsd_logp, "RDR_CleanupFileEntry Not a Directory dscp=0x%p",
1802                      dscp);
1803             if (code)
1804                 goto on_error;
1805         }
1806     }
1807
1808     Fid.cell   = FileId.Cell;
1809     Fid.volume = FileId.Volume;
1810     Fid.vnode  = FileId.Vnode;
1811     Fid.unique = FileId.Unique;
1812     Fid.hash   = FileId.Hash;
1813
1814     code = cm_GetSCache(&Fid, dscp ? &dscp->fid : NULL, &scp, userp, &req);
1815     if (code) {
1816         osi_Log1(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache object FID failure code=0x%x",
1817                  code);
1818         goto on_error;
1819     }
1820
1821     lock_ObtainWrite(&scp->rw);
1822     bScpLocked = TRUE;
1823     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1824                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1825     if (code) {
1826         osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure scp=0x%p code=0x%x",
1827                  scp, code);
1828         goto on_error;
1829     }
1830     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1831
1832     if (bLastHandle && (scp->fileType == CM_SCACHETYPE_FILE) &&
1833         scp->redirBufCount > 0)
1834     {
1835         LARGE_INTEGER heldExtents;
1836         AFSFileExtentCB extentList[1024];
1837         DWORD extentCount = 0;
1838         cm_buf_t *srbp;
1839         time_t now;
1840
1841         time(&now);
1842         heldExtents.QuadPart = 0;
1843
1844         for ( srbp = redirq_to_cm_buf_t(scp->redirQueueT);
1845               srbp;
1846               srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1847         {
1848             extentList[extentCount].Flags = 0;
1849             extentList[extentCount].Length = cm_data.blockSize;
1850             extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1851             extentList[extentCount].CacheOffset.QuadPart = srbp->datap - RDR_extentBaseAddress;
1852             lock_ObtainWrite(&buf_globalLock);
1853             srbp->redirReleaseRequested = now;
1854             lock_ReleaseWrite(&buf_globalLock);
1855             extentCount++;
1856
1857             if (extentCount == 1024) {
1858                 lock_ReleaseWrite(&scp->rw);
1859                 code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1860                 if (code) {
1861                     if (code == CM_ERROR_RETRY) {
1862                         /*
1863                          * The redirector either is not holding the extents or cannot let them
1864                          * go because they are otherwise in use.  At the moment, do nothing.
1865                          */
1866                     } else
1867                         break;
1868                 }
1869                 extentCount = 0;
1870                 bFlushFile = TRUE;
1871                 lock_ObtainWrite(&scp->rw);
1872             }
1873         }
1874
1875         if (code == 0 && extentCount > 0) {
1876             if (bScpLocked) {
1877                 lock_ReleaseWrite(&scp->rw);
1878                 bScpLocked = FALSE;
1879             }
1880             code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1881             bFlushFile = TRUE;
1882         }
1883     }
1884
1885     /* No longer in use by redirector */
1886     if (!bScpLocked) {
1887         lock_ObtainWrite(&scp->rw);
1888         bScpLocked = TRUE;
1889     }
1890
1891     if (bLastHandle) {
1892         lock_AssertWrite(&scp->rw);
1893         scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
1894     }
1895
1896     /* If not a readonly object, flush dirty data and update metadata */
1897     if (!(scp->flags & CM_SCACHEFLAG_RO)) {
1898         if ((scp->fileType == CM_SCACHETYPE_FILE) && (bLastHandle || bFlushFile)) {
1899             /* Serialize with any outstanding AsyncStore operation */
1900             code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_ASYNCSTORE);
1901             if (code == 0) {
1902                 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
1903
1904                 code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
1905                                  CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1906                 /*
1907                  * If we only have 'i' bits, then we should still be able to
1908                  * set flush the file.
1909                  */
1910                 if (code == CM_ERROR_NOACCESS && scp->creator == userp) {
1911                     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_INSERT,
1912                                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1913                 }
1914                 if (code == 0) {
1915                     if (bScpLocked) {
1916                         lock_ReleaseWrite(&scp->rw);
1917                         bScpLocked = FALSE;
1918                     }
1919
1920                     code = cm_FSync(scp, userp, &req, bScpLocked);
1921                 }
1922             }
1923             if (bLastHandle && code)
1924                 goto unlock;
1925         }
1926
1927         if (CleanupCB->ChangeTime.QuadPart) {
1928
1929             if (scp->fileType == CM_SCACHETYPE_FILE) {
1930                 /* Do not set length and other attributes at the same time */
1931                 if (scp->length.QuadPart != CleanupCB->AllocationSize.QuadPart) {
1932                     osi_Log2(afsd_logp, "RDR_CleanupFileEntry Length Change 0x%x -> 0x%x",
1933                              (afs_uint32)scp->length.QuadPart, (afs_uint32)CleanupCB->AllocationSize.QuadPart);
1934                     setAttr.mask |= CM_ATTRMASK_LENGTH;
1935                     setAttr.length.LowPart = CleanupCB->AllocationSize.LowPart;
1936                     setAttr.length.HighPart = CleanupCB->AllocationSize.HighPart;
1937
1938                     if (bScpLocked) {
1939                         lock_ReleaseWrite(&scp->rw);
1940                         bScpLocked = FALSE;
1941                     }
1942                     code = cm_SetAttr(scp, &setAttr, userp, &req);
1943                     if (code)
1944                         goto unlock;
1945                     setAttr.mask = 0;
1946                 }
1947             }
1948
1949             if (!bScpLocked) {
1950                 lock_ObtainWrite(&scp->rw);
1951                 bScpLocked = TRUE;
1952             }
1953
1954             if ((scp->unixModeBits & 0200) && (CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1955                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1956                 setAttr.unixModeBits = scp->unixModeBits & ~0222;
1957             } else if (!(scp->unixModeBits & 0200) && !(CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1958                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1959                 setAttr.unixModeBits = scp->unixModeBits | 0222;
1960             }
1961         }
1962
1963         if (CleanupCB->LastWriteTime.QuadPart) {
1964             ft.dwLowDateTime = CleanupCB->LastWriteTime.LowPart;
1965             ft.dwHighDateTime = CleanupCB->LastWriteTime.HighPart;
1966
1967             cm_UnixTimeFromLargeSearchTime(&clientModTime, &ft);
1968             if (scp->clientModTime != clientModTime) {
1969                 setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1970                 setAttr.clientModTime = clientModTime;
1971             }
1972         }
1973
1974         /* call setattr */
1975         if (setAttr.mask) {
1976             if (bScpLocked) {
1977                 lock_ReleaseWrite(&scp->rw);
1978                 bScpLocked = FALSE;
1979             }
1980             code = cm_SetAttr(scp, &setAttr, userp, &req);
1981         } else
1982             code = 0;
1983     }
1984
1985   unlock:
1986     /* Now drop the lock enforcing the share access */
1987     if ( CleanupCB->FileAccess != AFS_FILE_ACCESS_NOLOCK) {
1988         unsigned int sLockType;
1989         LARGE_INTEGER LOffset, LLength;
1990
1991         if (CleanupCB->FileAccess == AFS_FILE_ACCESS_SHARED)
1992             sLockType = LOCKING_ANDX_SHARED_LOCK;
1993         else
1994             sLockType = 0;
1995
1996         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, CleanupCB->Identifier);
1997
1998         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
1999         LOffset.LowPart = SMB_FID_QLOCK_LOW;
2000         LLength.HighPart = 0;
2001         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2002
2003         if (!bScpLocked) {
2004             lock_ObtainWrite(&scp->rw);
2005             bScpLocked = TRUE;
2006         }
2007
2008         code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
2009         if (code == 0)
2010         {
2011             code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
2012
2013             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
2014
2015             if (code == CM_ERROR_RANGE_NOT_LOCKED)
2016             {
2017                 osi_Log3(afsd_logp, "RDR_CleanupFileEntry Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
2018                          CleanupCB->FileAccess, CleanupCB->ProcessId, CleanupCB->Identifier);
2019
2020             }
2021         }
2022     }
2023
2024     if (bUnlockFile || bDeleteFile) {
2025         if (!bScpLocked) {
2026             lock_ObtainWrite(&scp->rw);
2027             bScpLocked = TRUE;
2028         }
2029         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2030                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2031         if (code) {
2032             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp (2) failure scp=0x%p code=0x%x",
2033                      scp, code);
2034             goto on_error;
2035         }
2036
2037         key = cm_GenerateKey(CM_SESSION_IFS, CleanupCB->ProcessId, 0);
2038
2039         /* the scp is now locked and current */
2040         code = cm_UnlockByKey(scp, key,
2041                               bDeleteFile ? CM_UNLOCK_FLAG_BY_FID : 0,
2042                               userp, &req);
2043
2044         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2045
2046         if (code)
2047             goto on_error;
2048     }
2049
2050   on_error:
2051     if (bDscpLocked)
2052         lock_ReleaseWrite(&dscp->rw);
2053     if (bScpLocked)
2054         lock_ReleaseWrite(&scp->rw);
2055
2056     if (code == 0 && dscp && bDeleteFile) {
2057         WCHAR FileName[260];
2058
2059         StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2060
2061         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2062             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2063         else
2064             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2065     }
2066
2067     if (code == 0) {
2068         if ( ResultBufferLength >=  sizeof( AFSFileCleanupResultCB))
2069         {
2070             (*ResultCB)->ResultBufferLength = sizeof( AFSFileCleanupResultCB);
2071             pResultCB = (AFSFileCleanupResultCB *)&(*ResultCB)->ResultData;
2072             pResultCB->ParentDataVersion.QuadPart = dscp ? dscp->dataVersion : 0;
2073         } else {
2074             (*ResultCB)->ResultBufferLength = 0;
2075         }
2076
2077         (*ResultCB)->ResultStatus = 0;
2078         osi_Log0(afsd_logp, "RDR_CleanupFileEntry SUCCESS");
2079     } else {
2080         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2081         (*ResultCB)->ResultStatus = status;
2082         osi_Log2(afsd_logp, "RDR_CleanupFileEntry FAILURE code=0x%x status=0x%x",
2083                   code, status);
2084     }
2085
2086     if (scp)
2087         cm_ReleaseSCache(scp);
2088     if (dscp)
2089         cm_ReleaseSCache(dscp);
2090
2091     return;
2092 }
2093
2094 void
2095 RDR_DeleteFileEntry( IN cm_user_t *userp,
2096                      IN AFSFileID ParentId,
2097                      IN ULONGLONG ProcessId,
2098                      IN WCHAR *FileNameCounted,
2099                      IN DWORD FileNameLength,
2100                      IN BOOL bWow64,
2101                      IN BOOL bCheckOnly,
2102                      IN DWORD ResultBufferLength,
2103                      IN OUT AFSCommResult **ResultCB)
2104 {
2105
2106     AFSFileDeleteResultCB *pResultCB = NULL;
2107     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2108     cm_fid_t            parentFid;
2109     afs_uint32          code;
2110     cm_scache_t *       dscp = NULL;
2111     cm_scache_t *       scp = NULL;
2112     afs_uint32          flags = 0;
2113     cm_attr_t           setAttr;
2114     cm_req_t            req;
2115     DWORD               status;
2116     wchar_t             FileName[260];
2117     cm_key_t            key;
2118
2119     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2120
2121     osi_Log4(afsd_logp, "RDR_DeleteFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2122               ParentId.Cell,  ParentId.Volume,
2123               ParentId.Vnode, ParentId.Unique);
2124     osi_Log2(afsd_logp, "... name=%S checkOnly=%x",
2125              osi_LogSaveStringW(afsd_logp, FileName),
2126              bCheckOnly);
2127
2128     RDR_InitReq(&req, bWow64);
2129     memset(&setAttr, 0, sizeof(cm_attr_t));
2130
2131     *ResultCB = (AFSCommResult *)malloc( size);
2132     if (!(*ResultCB)) {
2133         osi_Log0(afsd_logp, "RDR_DeleteFileEntry out of memory");
2134         return;
2135     }
2136
2137     memset( *ResultCB,
2138             '\0',
2139             size);
2140
2141     parentFid.cell   = ParentId.Cell;
2142     parentFid.volume = ParentId.Volume;
2143     parentFid.vnode  = ParentId.Vnode;
2144     parentFid.unique = ParentId.Unique;
2145     parentFid.hash   = ParentId.Hash;
2146
2147     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
2148     if (code) {
2149         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2150         if ( status == STATUS_INVALID_HANDLE)
2151             status = STATUS_OBJECT_PATH_INVALID;
2152         (*ResultCB)->ResultStatus = status;
2153         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
2154                   code, status);
2155         return;
2156     }
2157
2158     lock_ObtainWrite(&dscp->rw);
2159
2160     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
2161                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2162     if (code) {
2163         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2164         (*ResultCB)->ResultStatus = status;
2165         (*ResultCB)->ResultBufferLength = 0;
2166         lock_ReleaseWrite(&dscp->rw);
2167         cm_ReleaseSCache(dscp);
2168         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
2169                  dscp, code, status);
2170         return;
2171     }
2172
2173     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2174     lock_ReleaseWrite(&dscp->rw);
2175
2176     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2177         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2178         cm_ReleaseSCache(dscp);
2179         osi_Log1(afsd_logp, "RDR_DeleteFileEntry Not a Directory dscp=0x%p",
2180                  dscp);
2181         return;
2182     }
2183
2184     code = cm_Lookup(dscp, FileName, 0, userp, &req, &scp);
2185     if (code) {
2186         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2187         (*ResultCB)->ResultStatus = status;
2188         (*ResultCB)->ResultBufferLength = 0;
2189         cm_ReleaseSCache(dscp);
2190         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_Lookup failure code=0x%x status=0x%x",
2191                  code, status);
2192         return;
2193     }
2194
2195     lock_ObtainWrite(&scp->rw);
2196     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_DELETE,
2197                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2198     if (code) {
2199         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2200         (*ResultCB)->ResultStatus = status;
2201         (*ResultCB)->ResultBufferLength = 0;
2202         lock_ReleaseWrite(&scp->rw);
2203         cm_ReleaseSCache(scp);
2204         cm_ReleaseSCache(dscp);
2205         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2206                  scp, code, status);
2207         return;
2208     }
2209
2210     if (!bCheckOnly) {
2211         /* Drop all locks since the file is being deleted */
2212         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2213                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2214         if (code) {
2215             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2216             (*ResultCB)->ResultStatus = status;
2217             (*ResultCB)->ResultBufferLength = 0;
2218             lock_ReleaseWrite(&scp->rw);
2219             cm_ReleaseSCache(scp);
2220             cm_ReleaseSCache(dscp);
2221             osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp Lock failure scp=0x%p code=0x%x status=0x%x",
2222                      scp, code, status);
2223         }
2224
2225         /* the scp is now locked and current */
2226         key = cm_GenerateKey(CM_SESSION_IFS, ProcessId, 0);
2227
2228         code = cm_UnlockByKey(scp, key,
2229                               CM_UNLOCK_FLAG_BY_FID,
2230                               userp, &req);
2231
2232         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2233         lock_ReleaseWrite(&scp->rw);
2234
2235         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2236             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2237         else
2238             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2239     } else {
2240         lock_ReleaseWrite(&scp->rw);
2241     }
2242
2243     if (code == 0) {
2244         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
2245
2246         (*ResultCB)->ResultBufferLength = sizeof( AFSFileDeleteResultCB);
2247
2248         pResultCB = (AFSFileDeleteResultCB *)(*ResultCB)->ResultData;
2249
2250         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
2251         osi_Log0(afsd_logp, "RDR_DeleteFileEntry SUCCESS");
2252     } else {
2253         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2254         (*ResultCB)->ResultStatus = status;
2255         (*ResultCB)->ResultBufferLength = 0;
2256         osi_Log2(afsd_logp, "RDR_DeleteFileEntry FAILURE code=0x%x status=0x%x",
2257                   code, status);
2258     }
2259
2260     cm_ReleaseSCache(dscp);
2261     cm_ReleaseSCache(scp);
2262
2263     return;
2264 }
2265
2266 void
2267 RDR_RenameFileEntry( IN cm_user_t *userp,
2268                      IN WCHAR    *SourceFileNameCounted,
2269                      IN DWORD     SourceFileNameLength,
2270                      IN AFSFileID SourceFileId,
2271                      IN AFSFileRenameCB *pRenameCB,
2272                      IN BOOL bWow64,
2273                      IN DWORD ResultBufferLength,
2274                      IN OUT AFSCommResult **ResultCB)
2275 {
2276
2277     AFSFileRenameResultCB *pResultCB = NULL;
2278     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2279     AFSFileID              SourceParentId   = pRenameCB->SourceParentId;
2280     AFSFileID              TargetParentId   = pRenameCB->TargetParentId;
2281     WCHAR *                TargetFileNameCounted = pRenameCB->TargetName;
2282     DWORD                  TargetFileNameLength = pRenameCB->TargetNameLength;
2283     cm_fid_t               SourceParentFid;
2284     cm_fid_t               TargetParentFid;
2285     cm_fid_t               SourceFid;
2286     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2287     cm_fid_t               TargetFid;
2288     cm_scache_t *          oldDscp;
2289     cm_scache_t *          newDscp;
2290     cm_dirOp_t dirop;
2291     wchar_t                shortName[13];
2292     wchar_t                SourceFileName[260];
2293     wchar_t                TargetFileName[260];
2294     cm_dirFid_t            dfid;
2295     cm_req_t               req;
2296     afs_uint32             code;
2297     DWORD                  status;
2298
2299     RDR_InitReq(&req, bWow64);
2300
2301     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2302     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2303
2304     osi_Log4(afsd_logp, "RDR_RenameFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2305               SourceParentId.Cell,  SourceParentId.Volume,
2306               SourceParentId.Vnode, SourceParentId.Unique);
2307     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2308     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2309               TargetParentId.Cell,  TargetParentId.Volume,
2310               TargetParentId.Vnode, TargetParentId.Unique);
2311     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2312
2313     *ResultCB = (AFSCommResult *)malloc( size);
2314     if (!(*ResultCB))
2315         return;
2316
2317     memset( *ResultCB,
2318             '\0',
2319             size);
2320
2321     pResultCB = (AFSFileRenameResultCB *)(*ResultCB)->ResultData;
2322
2323     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2324     {
2325         osi_Log2(afsd_logp, "RDR_RenameFileEntry Invalid Name Length: src %u target %u",
2326                  SourceFileNameLength, TargetFileNameLength);
2327         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2328         return;
2329     }
2330
2331     SourceParentFid.cell   = SourceParentId.Cell;
2332     SourceParentFid.volume = SourceParentId.Volume;
2333     SourceParentFid.vnode  = SourceParentId.Vnode;
2334     SourceParentFid.unique = SourceParentId.Unique;
2335     SourceParentFid.hash   = SourceParentId.Hash;
2336
2337     TargetParentFid.cell   = TargetParentId.Cell;
2338     TargetParentFid.volume = TargetParentId.Volume;
2339     TargetParentFid.vnode  = TargetParentId.Vnode;
2340     TargetParentFid.unique = TargetParentId.Unique;
2341     TargetParentFid.hash   = TargetParentId.Hash;
2342
2343     code = cm_GetSCache(&SourceParentFid, NULL, &oldDscp, userp, &req);
2344     if (code) {
2345         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache source parent failed code 0x%x", code);
2346         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2347         if ( status == STATUS_INVALID_HANDLE)
2348             status = STATUS_OBJECT_PATH_INVALID;
2349         (*ResultCB)->ResultStatus = status;
2350         return;
2351     }
2352
2353     lock_ObtainWrite(&oldDscp->rw);
2354     code = cm_SyncOp(oldDscp, NULL, userp, &req, 0,
2355                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2356     if (code) {
2357         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp oldDscp 0x%p failed code 0x%x", oldDscp, code);
2358         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2359         if ( status == STATUS_INVALID_HANDLE)
2360             status = STATUS_OBJECT_PATH_INVALID;
2361         (*ResultCB)->ResultStatus = status;
2362         lock_ReleaseWrite(&oldDscp->rw);
2363         cm_ReleaseSCache(oldDscp);
2364         return;
2365     }
2366
2367     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2368     lock_ReleaseWrite(&oldDscp->rw);
2369
2370
2371     if (oldDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2372         osi_Log1(afsd_logp, "RDR_RenameFileEntry oldDscp 0x%p not a directory", oldDscp);
2373         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2374         cm_ReleaseSCache(oldDscp);
2375         return;
2376     }
2377
2378     code = cm_GetSCache(&TargetParentFid, NULL, &newDscp, userp, &req);
2379     if (code) {
2380         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target parent failed code 0x%x", code);
2381         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2382         (*ResultCB)->ResultStatus = status;
2383         cm_ReleaseSCache(oldDscp);
2384         return;
2385     }
2386
2387     lock_ObtainWrite(&newDscp->rw);
2388     code = cm_SyncOp(newDscp, NULL, userp, &req, 0,
2389                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2390     if (code) {
2391         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp newDscp 0x%p failed code 0x%x", newDscp, code);
2392         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2393         (*ResultCB)->ResultStatus = status;
2394         lock_ReleaseWrite(&newDscp->rw);
2395         cm_ReleaseSCache(oldDscp);
2396         cm_ReleaseSCache(newDscp);
2397         return;
2398     }
2399
2400     cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2401     lock_ReleaseWrite(&newDscp->rw);
2402
2403
2404     if (newDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2405         osi_Log1(afsd_logp, "RDR_RenameFileEntry newDscp 0x%p not a directory", newDscp);
2406         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2407         cm_ReleaseSCache(oldDscp);
2408         cm_ReleaseSCache(newDscp);
2409         return;
2410     }
2411
2412     /* Obtain the original FID just for debugging purposes */
2413     code = cm_BeginDirOp( oldDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2414     if (code == 0) {
2415         code = cm_BPlusDirLookup(&dirop, SourceFileName, &SourceFid);
2416         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2417         cm_EndDirOp(&dirop);
2418     }
2419
2420     code = cm_Rename( oldDscp, NULL, SourceFileName,
2421                       newDscp, TargetFileName, userp, &req);
2422     if (code == 0) {
2423         cm_scache_t *scp = 0;
2424         DWORD dwRemaining;
2425
2426         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2427         dwRemaining = ResultBufferLength - sizeof( AFSFileRenameResultCB) + sizeof( AFSDirEnumEntry);
2428         (*ResultCB)->ResultStatus = 0;
2429
2430         pResultCB->SourceParentDataVersion.QuadPart = oldDscp->dataVersion;
2431         pResultCB->TargetParentDataVersion.QuadPart = newDscp->dataVersion;
2432
2433         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p SUCCESS",
2434                  oldDscp, newDscp);
2435
2436         code = cm_BeginDirOp( newDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2437         if (code == 0) {
2438             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2439             cm_EndDirOp(&dirop);
2440         }
2441
2442         if (code != 0) {
2443             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_BPlusDirLookup failed code 0x%x",
2444                      code);
2445             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2446             cm_ReleaseSCache(oldDscp);
2447             cm_ReleaseSCache(newDscp);
2448             return;
2449         }
2450
2451         osi_Log4(afsd_logp, "RDR_RenameFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2452                   TargetFid.cell,  TargetFid.volume,
2453                   TargetFid.vnode, TargetFid.unique);
2454
2455         code = cm_GetSCache(&TargetFid, &newDscp->fid, &scp, userp, &req);
2456         if (code) {
2457             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target failed code 0x%x", code);
2458             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2459             (*ResultCB)->ResultStatus = status;
2460             cm_ReleaseSCache(oldDscp);
2461             cm_ReleaseSCache(newDscp);
2462             return;
2463         }
2464
2465         /* Make sure the source vnode is current */
2466         lock_ObtainWrite(&scp->rw);
2467         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2468                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2469         if (code) {
2470             osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp scp 0x%p failed code 0x%x", scp, code);
2471             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2472             (*ResultCB)->ResultStatus = status;
2473             lock_ReleaseWrite(&scp->rw);
2474             cm_ReleaseSCache(oldDscp);
2475             cm_ReleaseSCache(newDscp);
2476             cm_ReleaseSCache(scp);
2477             return;
2478         }
2479
2480         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2481         lock_ReleaseWrite(&scp->rw);
2482
2483         if (cm_shortNames) {
2484             dfid.vnode = htonl(scp->fid.vnode);
2485             dfid.unique = htonl(scp->fid.unique);
2486
2487             if (!cm_Is8Dot3(TargetFileName))
2488                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2489             else
2490                 shortName[0] = '\0';
2491         }
2492
2493         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2494                                  newDscp, scp, userp, &req, TargetFileName, shortName,
2495                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2496                                  0, NULL, &dwRemaining);
2497         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2498         cm_ReleaseSCache(scp);
2499
2500         osi_Log0(afsd_logp, "RDR_RenameFileEntry SUCCESS");
2501     } else {
2502         osi_Log3(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p failed code 0x%x",
2503                  oldDscp, newDscp, code);
2504         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2505         (*ResultCB)->ResultStatus = status;
2506         (*ResultCB)->ResultBufferLength = 0;
2507     }
2508
2509     cm_ReleaseSCache(oldDscp);
2510     cm_ReleaseSCache(newDscp);
2511     return;
2512 }
2513
2514 /*
2515  * AFS does not support cross-directory hard links but RDR_HardLinkFileEntry
2516  * is written as if AFS does.  The check for cross-directory links is
2517  * implemented in cm_Link().
2518  *
2519  * Windows supports optional ReplaceIfExists functionality.  The AFS file
2520  * server does not.  If the target name already exists and bReplaceIfExists
2521  * is true, check to see if the user has insert permission before calling
2522  * cm_Unlink() on the existing object.  If the user does not have insert
2523  * permission return STATUS_ACCESS_DENIED.
2524  */
2525
2526 void
2527 RDR_HardLinkFileEntry( IN cm_user_t *userp,
2528                        IN WCHAR    *SourceFileNameCounted,
2529                        IN DWORD     SourceFileNameLength,
2530                        IN AFSFileID SourceFileId,
2531                        IN AFSFileHardLinkCB *pHardLinkCB,
2532                        IN BOOL bWow64,
2533                        IN DWORD ResultBufferLength,
2534                        IN OUT AFSCommResult **ResultCB)
2535 {
2536
2537     AFSFileHardLinkResultCB *pResultCB = NULL;
2538     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2539     AFSFileID              SourceParentId   = pHardLinkCB->SourceParentId;
2540     AFSFileID              TargetParentId   = pHardLinkCB->TargetParentId;
2541     WCHAR *                TargetFileNameCounted = pHardLinkCB->TargetName;
2542     DWORD                  TargetFileNameLength = pHardLinkCB->TargetNameLength;
2543     cm_fid_t               SourceParentFid;
2544     cm_fid_t               TargetParentFid;
2545     cm_fid_t               SourceFid;
2546     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2547     cm_scache_t *          srcDscp = NULL;
2548     cm_scache_t *          targetDscp = NULL;
2549     cm_scache_t *          srcScp = NULL;
2550     cm_dirOp_t             dirop;
2551     wchar_t                shortName[13];
2552     wchar_t                SourceFileName[260];
2553     wchar_t                TargetFileName[260];
2554     cm_dirFid_t            dfid;
2555     cm_req_t               req;
2556     afs_uint32             code;
2557     DWORD                  status;
2558
2559     RDR_InitReq(&req, bWow64);
2560
2561     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2562     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2563
2564     osi_Log4(afsd_logp, "RDR_HardLinkFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2565               SourceParentId.Cell,  SourceParentId.Volume,
2566               SourceParentId.Vnode, SourceParentId.Unique);
2567     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2568     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2569               TargetParentId.Cell,  TargetParentId.Volume,
2570               TargetParentId.Vnode, TargetParentId.Unique);
2571     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2572
2573     *ResultCB = (AFSCommResult *)malloc( size);
2574     if (!(*ResultCB))
2575         return;
2576
2577     memset( *ResultCB,
2578             '\0',
2579             size);
2580
2581     pResultCB = (AFSFileHardLinkResultCB *)(*ResultCB)->ResultData;
2582
2583     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2584     {
2585         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry Invalid Name Length: src %u target %u",
2586                  SourceFileNameLength, TargetFileNameLength);
2587         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2588         return;
2589     }
2590
2591     SourceFid.cell   = SourceFileId.Cell;
2592     SourceFid.volume = SourceFileId.Volume;
2593     SourceFid.vnode  = SourceFileId.Vnode;
2594     SourceFid.unique = SourceFileId.Unique;
2595     SourceFid.hash   = SourceFileId.Hash;
2596
2597     SourceParentFid.cell   = SourceParentId.Cell;
2598     SourceParentFid.volume = SourceParentId.Volume;
2599     SourceParentFid.vnode  = SourceParentId.Vnode;
2600     SourceParentFid.unique = SourceParentId.Unique;
2601     SourceParentFid.hash   = SourceParentId.Hash;
2602
2603     TargetParentFid.cell   = TargetParentId.Cell;
2604     TargetParentFid.volume = TargetParentId.Volume;
2605     TargetParentFid.vnode  = TargetParentId.Vnode;
2606     TargetParentFid.unique = TargetParentId.Unique;
2607     TargetParentFid.hash   = TargetParentId.Hash;
2608
2609     code = cm_GetSCache(&SourceFid, NULL, &srcScp, userp, &req);
2610     if (code) {
2611         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache source failed code 0x%x", code);
2612         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2613         (*ResultCB)->ResultStatus = status;
2614         return;
2615     }
2616
2617     code = cm_GetSCache(&TargetParentFid, NULL, &targetDscp, userp, &req);
2618     if (code) {
2619         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache target parent failed code 0x%x", code);
2620         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2621         (*ResultCB)->ResultStatus = status;
2622         cm_ReleaseSCache(srcScp);
2623         return;
2624     }
2625
2626     lock_ObtainWrite(&targetDscp->rw);
2627     code = cm_SyncOp(targetDscp, NULL, userp, &req, PRSFS_INSERT,
2628                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2629     if (code) {
2630         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp targetDscp 0x%p failed code 0x%x", targetDscp, code);
2631         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2632         (*ResultCB)->ResultStatus = status;
2633         lock_ReleaseWrite(&targetDscp->rw);
2634         cm_ReleaseSCache(srcScp);
2635         cm_ReleaseSCache(targetDscp);
2636         return;
2637     }
2638
2639     cm_SyncOpDone(targetDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2640     lock_ReleaseWrite(&targetDscp->rw);
2641
2642     if (targetDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2643         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry targetDscp 0x%p not a directory", targetDscp);
2644         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2645         cm_ReleaseSCache(srcScp);
2646         cm_ReleaseSCache(targetDscp);
2647         return;
2648     }
2649
2650     if ( cm_FidCmp(&SourceParentFid, &TargetParentFid) ) {
2651         code = cm_GetSCache(&SourceParentFid, NULL, &srcDscp, userp, &req);
2652         if (code) {
2653             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache source parent failed code 0x%x", code);
2654             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2655             if ( status == STATUS_INVALID_HANDLE)
2656                 status = STATUS_OBJECT_PATH_INVALID;
2657             (*ResultCB)->ResultStatus = status;
2658             cm_ReleaseSCache(srcScp);
2659             cm_ReleaseSCache(targetDscp);
2660             return;
2661         }
2662
2663         lock_ObtainWrite(&srcDscp->rw);
2664         code = cm_SyncOp(srcDscp, NULL, userp, &req, 0,
2665                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2666         if (code) {
2667             osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp srcDscp 0x%p failed code 0x%x", srcDscp, code);
2668             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2669             if ( status == STATUS_INVALID_HANDLE)
2670                 status = STATUS_OBJECT_PATH_INVALID;
2671             (*ResultCB)->ResultStatus = status;
2672             lock_ReleaseWrite(&srcDscp->rw);
2673             if (srcDscp != targetDscp)
2674                 cm_ReleaseSCache(srcDscp);
2675             cm_ReleaseSCache(targetDscp);
2676             cm_ReleaseSCache(srcScp);
2677             return;
2678         }
2679
2680         cm_SyncOpDone(srcDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2681         lock_ReleaseWrite(&srcDscp->rw);
2682
2683         if (srcDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2684             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry srcDscp 0x%p not a directory", srcDscp);
2685             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2686             if (srcDscp != targetDscp)
2687                 cm_ReleaseSCache(srcDscp);
2688             cm_ReleaseSCache(targetDscp);
2689             cm_ReleaseSCache(srcScp);
2690             return;
2691         }
2692     } else {
2693         srcDscp = targetDscp;
2694     }
2695
2696     /* Obtain the target FID if it exists */
2697     code = cm_BeginDirOp( targetDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2698     if (code == 0) {
2699         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2700         cm_EndDirOp(&dirop);
2701     }
2702
2703     if (OrigTargetFid.vnode) {
2704
2705         /* An object exists with the target name */
2706         if (!pHardLinkCB->bReplaceIfExists) {
2707             osi_Log0(afsd_logp, "RDR_HardLinkFileEntry target name collision and !ReplaceIfExists");
2708             (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_COLLISION;
2709             if (srcDscp != targetDscp)
2710                 cm_ReleaseSCache(srcDscp);
2711             cm_ReleaseSCache(targetDscp);
2712             cm_ReleaseSCache(srcScp);
2713             return;
2714         }
2715
2716         lock_ObtainWrite(&targetDscp->rw);
2717         code = cm_SyncOp(targetDscp, NULL, userp, &req, PRSFS_INSERT | PRSFS_DELETE,
2718                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2719         if (code) {
2720             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2721             (*ResultCB)->ResultStatus = status;
2722             lock_ReleaseWrite(&srcDscp->rw);
2723             if (srcDscp != targetDscp)
2724                 cm_ReleaseSCache(srcDscp);
2725             cm_ReleaseSCache(targetDscp);
2726             cm_ReleaseSCache(srcScp);
2727             return;
2728         }
2729         cm_SyncOpDone(targetDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2730         lock_ReleaseWrite(&targetDscp->rw);
2731
2732         code = cm_Unlink(targetDscp, NULL, TargetFileName, userp, &req);
2733         if (code) {
2734             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_Unlink code 0x%x", code);
2735             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2736             (*ResultCB)->ResultStatus = status;
2737             lock_ReleaseWrite(&srcDscp->rw);
2738             if (srcDscp != targetDscp)
2739                 cm_ReleaseSCache(srcDscp);
2740             cm_ReleaseSCache(targetDscp);
2741             cm_ReleaseSCache(srcScp);
2742             return;
2743         }
2744     }
2745
2746     code = cm_Link( targetDscp, TargetFileName, srcScp, 0, userp, &req);
2747     if (code == 0) {
2748         cm_fid_t TargetFid;
2749         cm_scache_t *targetScp = 0;
2750         DWORD dwRemaining;
2751
2752         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2753         dwRemaining = ResultBufferLength - sizeof( AFSFileHardLinkResultCB) + sizeof( AFSDirEnumEntry);
2754         (*ResultCB)->ResultStatus = 0;
2755
2756         pResultCB->SourceParentDataVersion.QuadPart = srcDscp->dataVersion;
2757         pResultCB->TargetParentDataVersion.QuadPart = targetDscp->dataVersion;
2758
2759         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_Link srcDscp 0x%p targetDscp 0x%p SUCCESS",
2760                  srcDscp, targetDscp);
2761
2762         code = cm_BeginDirOp( targetDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2763         if (code == 0) {
2764             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2765             cm_EndDirOp(&dirop);
2766         }
2767
2768         if (code != 0) {
2769             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_BPlusDirLookup failed code 0x%x",
2770                      code);
2771             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2772             if (srcDscp != targetDscp)
2773                 cm_ReleaseSCache(srcDscp);
2774             cm_ReleaseSCache(srcScp);
2775             cm_ReleaseSCache(targetDscp);
2776             return;
2777         }
2778
2779         osi_Log4(afsd_logp, "RDR_HardLinkFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2780                   TargetFid.cell,  TargetFid.volume,
2781                   TargetFid.vnode, TargetFid.unique);
2782
2783         code = cm_GetSCache(&TargetFid, &targetDscp->fid, &targetScp, userp, &req);
2784         if (code) {
2785             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache target failed code 0x%x", code);
2786             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2787             (*ResultCB)->ResultStatus = status;
2788             if (srcDscp != targetDscp)
2789                 cm_ReleaseSCache(srcDscp);
2790             cm_ReleaseSCache(srcScp);
2791             cm_ReleaseSCache(targetDscp);
2792             return;
2793         }
2794
2795         /* Make sure the source vnode is current */
2796         lock_ObtainWrite(&targetScp->rw);
2797         code = cm_SyncOp(targetScp, NULL, userp, &req, 0,
2798                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2799         if (code) {
2800             osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp scp 0x%p failed code 0x%x",
2801                      targetScp, code);
2802             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2803             (*ResultCB)->ResultStatus = status;
2804             lock_ReleaseWrite(&targetScp->rw);
2805             cm_ReleaseSCache(targetScp);
2806             if (srcDscp != targetDscp)
2807                 cm_ReleaseSCache(srcDscp);
2808             cm_ReleaseSCache(srcScp);
2809             cm_ReleaseSCache(targetDscp);
2810             return;
2811         }
2812
2813         cm_SyncOpDone(targetScp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2814         lock_ReleaseWrite(&targetScp->rw);
2815
2816         if (cm_shortNames) {
2817             dfid.vnode = htonl(targetScp->fid.vnode);
2818             dfid.unique = htonl(targetScp->fid.unique);
2819
2820             if (!cm_Is8Dot3(TargetFileName))
2821                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2822             else
2823                 shortName[0] = '\0';
2824         }
2825
2826         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2827                                  targetDscp, targetScp, userp, &req, TargetFileName, shortName,
2828                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2829                                  0, NULL, &dwRemaining);
2830         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2831         cm_ReleaseSCache(targetScp);
2832
2833         osi_Log0(afsd_logp, "RDR_HardLinkFileEntry SUCCESS");
2834     } else {
2835         osi_Log3(afsd_logp, "RDR_HardLinkFileEntry cm_Link srcDscp 0x%p targetDscp 0x%p failed code 0x%x",
2836                  srcDscp, targetDscp, code);
2837         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2838         (*ResultCB)->ResultStatus = status;
2839         (*ResultCB)->ResultBufferLength = 0;
2840     }
2841
2842     cm_ReleaseSCache(srcScp);
2843     if (srcDscp != targetDscp)
2844         cm_ReleaseSCache(srcDscp);
2845     cm_ReleaseSCache(targetDscp);
2846     return;
2847 }
2848
2849 void
2850 RDR_FlushFileEntry( IN cm_user_t *userp,
2851                     IN AFSFileID FileId,
2852                     IN BOOL bWow64,
2853                     IN DWORD ResultBufferLength,
2854                     IN OUT AFSCommResult **ResultCB)
2855 {
2856     cm_scache_t *scp = NULL;
2857     cm_fid_t    Fid;
2858     afs_uint32  code;
2859     cm_req_t    req;
2860     DWORD       status;
2861 #ifdef ODS_DEBUG
2862     char        dbgstr[1024];
2863 #endif
2864
2865     RDR_InitReq(&req, bWow64);
2866
2867     osi_Log4(afsd_logp, "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x",
2868               FileId.Cell, FileId.Volume,
2869               FileId.Vnode, FileId.Unique);
2870 #ifdef ODS_DEBUG
2871     snprintf( dbgstr, 1024,
2872               "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x\n",
2873               FileId.Cell, FileId.Volume,
2874               FileId.Vnode, FileId.Unique);
2875     OutputDebugStringA( dbgstr);
2876 #endif
2877
2878     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2879     if (!(*ResultCB)) {
2880         osi_Log0(afsd_logp, "RDR_FlushFileEntry out of memory");
2881         return;
2882     }
2883
2884     memset( *ResultCB,
2885             '\0',
2886             sizeof( AFSCommResult));
2887
2888     /* Process the release */
2889     Fid.cell = FileId.Cell;
2890     Fid.volume = FileId.Volume;
2891     Fid.vnode = FileId.Vnode;
2892     Fid.unique = FileId.Unique;
2893     Fid.hash = FileId.Hash;
2894
2895     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2896     if (code) {
2897         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2898         (*ResultCB)->ResultStatus = status;
2899         osi_Log2(afsd_logp, "RDR_FlushFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2900                   code, status);
2901         return;
2902     }
2903
2904     lock_ObtainWrite(&scp->rw);
2905     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2906         lock_ReleaseWrite(&scp->rw);
2907         (*ResultCB)->ResultStatus = STATUS_INVALID_HANDLE;
2908         return;
2909     }
2910
2911     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2912                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2913     if (code) {
2914         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2915         (*ResultCB)->ResultStatus = status;
2916         lock_ReleaseWrite(&scp->rw);
2917         cm_ReleaseSCache(scp);
2918         osi_Log3(afsd_logp, "RDR_FlushFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2919                  scp, code, status);
2920         return;
2921     }
2922
2923     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2924     lock_ReleaseWrite(&scp->rw);
2925
2926     code = cm_FSync(scp, userp, &req, FALSE);
2927     cm_ReleaseSCache(scp);
2928
2929     if (code) {
2930         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2931         (*ResultCB)->ResultStatus = status;
2932         osi_Log2(afsd_logp, "RDR_FlushFileEntry FAILURE code=0x%x status=0x%x",
2933                   code, status);
2934     } else {
2935         (*ResultCB)->ResultStatus = 0;
2936         osi_Log0(afsd_logp, "RDR_FlushFileEntry SUCCESS");
2937     }
2938     (*ResultCB)->ResultBufferLength = 0;
2939
2940     return;
2941 }
2942
2943 afs_uint32
2944 RDR_CheckAccess( IN cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
2945                  ULONG access,
2946                  ULONG *granted)
2947 {
2948     ULONG afs_acc, afs_gr;
2949     BOOLEAN file, dir;
2950     afs_uint32 code = 0;
2951
2952     file = (scp->fileType == CM_SCACHETYPE_FILE);
2953     dir = !file;
2954
2955     /* access definitions from prs_fs.h */
2956     afs_acc = 0;
2957     if (access & FILE_READ_DATA)
2958         afs_acc |= PRSFS_READ;
2959     if (access & FILE_READ_EA || access & FILE_READ_ATTRIBUTES)
2960         afs_acc |= PRSFS_READ;
2961     if (file && ((access & FILE_WRITE_DATA) || (access & FILE_APPEND_DATA)))
2962         afs_acc |= PRSFS_WRITE;
2963     if (access & FILE_WRITE_EA || access & FILE_WRITE_ATTRIBUTES)
2964         afs_acc |= PRSFS_WRITE;
2965     if (dir && ((access & FILE_ADD_FILE) || (access & FILE_ADD_SUBDIRECTORY)))
2966         afs_acc |= PRSFS_INSERT;
2967     if (dir && (access & FILE_LIST_DIRECTORY))
2968         afs_acc |= PRSFS_LOOKUP;
2969     if (file && (access & FILE_EXECUTE))
2970         afs_acc |= PRSFS_WRITE;
2971     if (dir && (access & FILE_TRAVERSE))
2972         afs_acc |= PRSFS_READ;
2973     if (dir && (access & FILE_DELETE_CHILD))
2974         afs_acc |= PRSFS_DELETE;
2975     if ((access & DELETE))
2976         afs_acc |= PRSFS_DELETE;
2977
2978     /* check ACL with server */
2979     lock_ObtainWrite(&scp->rw);
2980     while (1)
2981     {
2982         if (cm_HaveAccessRights(scp, userp, reqp, afs_acc, &afs_gr))
2983         {
2984             break;
2985         }
2986         else
2987         {
2988             /* we don't know the required access rights */
2989             code = cm_GetAccessRights(scp, userp, reqp);
2990             if (code)
2991                 break;
2992             continue;
2993         }
2994     }
2995     lock_ReleaseWrite(&(scp->rw));
2996
2997     if (code == 0) {
2998         *granted = 0;
2999         if (afs_gr & PRSFS_READ)
3000             *granted |= FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_EXECUTE;
3001         if (afs_gr & PRSFS_WRITE)
3002             *granted |= FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_EXECUTE;
3003         if (afs_gr & PRSFS_INSERT)
3004             *granted |= (dir ? FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY : 0) | (file ? FILE_ADD_SUBDIRECTORY : 0);
3005         if (afs_gr & PRSFS_LOOKUP)
3006             *granted |= (dir ? FILE_LIST_DIRECTORY : 0);
3007         if (afs_gr & PRSFS_DELETE)
3008             *granted |= FILE_DELETE_CHILD | DELETE;
3009         if (afs_gr & PRSFS_LOCK)
3010             *granted |= 0;
3011         if (afs_gr & PRSFS_ADMINISTER)
3012             *granted |= 0;
3013
3014         *granted |= SYNCHRONIZE | READ_CONTROL;
3015
3016         /* don't give more access than what was requested */
3017         *granted &= access;
3018         osi_Log3(afsd_logp, "RDR_CheckAccess SUCCESS scp=0x%p requested=0x%x granted=0x%x", scp, access, *granted);
3019     } else
3020         osi_Log2(afsd_logp, "RDR_CheckAccess FAILURE scp=0x%p code=0x%x",
3021                  scp, code);
3022
3023     return code;
3024 }
3025
3026 void
3027 RDR_OpenFileEntry( IN cm_user_t *userp,
3028                    IN AFSFileID FileId,
3029                    IN AFSFileOpenCB *OpenCB,
3030                    IN BOOL bWow64,
3031                    IN BOOL bHoldFid,
3032                    IN DWORD ResultBufferLength,
3033                    IN OUT AFSCommResult **ResultCB)
3034 {
3035     AFSFileOpenResultCB *pResultCB = NULL;
3036     cm_scache_t *scp = NULL;
3037     cm_user_t   *sysUserp = NULL;
3038     cm_fid_t    Fid;
3039     cm_lock_data_t      *ldp = NULL;
3040     afs_uint32  code;
3041     cm_req_t    req;
3042     DWORD       status;
3043
3044     RDR_InitReq(&req, bWow64);
3045
3046     osi_Log4(afsd_logp, "RDR_OpenFileEntry File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3047               FileId.Cell, FileId.Volume,
3048               FileId.Vnode, FileId.Unique);
3049
3050     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
3051     if (!(*ResultCB)) {
3052         osi_Log0(afsd_logp, "RDR_OpenFileEntry out of memory");
3053         return;
3054     }
3055
3056     memset( *ResultCB,
3057             '\0',
3058             sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
3059
3060     pResultCB = (AFSFileOpenResultCB *)(*ResultCB)->ResultData;
3061
3062     /* Process the release */
3063     Fid.cell = FileId.Cell;
3064     Fid.volume = FileId.Volume;
3065     Fid.vnode = FileId.Vnode;
3066     Fid.unique = FileId.Unique;
3067     Fid.hash = FileId.Hash;
3068
3069     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3070     if (code) {
3071         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3072         (*ResultCB)->ResultStatus = status;
3073         osi_Log2(afsd_logp, "RDR_OpenFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
3074                   code, status);
3075         return;
3076     }
3077
3078     lock_ObtainWrite(&scp->rw);
3079     code = cm_SyncOp(scp, NULL, userp, &req, 0,
3080                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3081     if (code) {
3082         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3083         (*ResultCB)->ResultStatus = status;
3084         lock_ReleaseWrite(&scp->rw);
3085         cm_ReleaseSCache(scp);
3086         osi_Log3(afsd_logp, "RDR_OpenFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
3087                  scp, code, status);
3088         return;
3089     }
3090
3091     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3092     lock_ReleaseWrite(&scp->rw);
3093
3094     sysUserp = RDR_GetLocalSystemUser();
3095
3096     /*
3097      * Skip the open check if the request is coming from the local system account.
3098      * The local system has no tokens and therefore any requests sent to a file
3099      * server will fail.  Unfortunately, there are special system processes that
3100      * perform actions on files and directories in preparation for memory mapping
3101      * executables.  If the open check fails, the real request from the user process
3102      * will never be issued.
3103      *
3104      * Permitting the file system to allow subsequent operations to proceed does
3105      * not compromise security.  All requests to obtain file data or directory
3106      * enumerations will subsequently fail if they are not submitted under the
3107      * context of a process for that have access to the necessary credentials.
3108      */
3109
3110     if ( userp == sysUserp)
3111     {
3112         osi_Log1(afsd_logp, "RDR_OpenFileEntry LOCAL_SYSTEM access check skipped scp=0x%p",
3113                  scp);
3114         pResultCB->GrantedAccess = OpenCB->DesiredAccess;
3115         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3116         code = 0;
3117     }
3118     else
3119     {
3120         int count = 0;
3121
3122         do {
3123             if (count++ > 0) {
3124                 Sleep(350);
3125                 osi_Log3(afsd_logp,
3126                          "RDR_OpenFileEntry repeating open check scp=0x%p userp=0x%p code=0x%x",
3127                          scp, userp, code);
3128             }
3129             code = cm_CheckNTOpen(scp, OpenCB->DesiredAccess, OpenCB->ShareAccess,
3130                                   OPEN_ALWAYS,
3131                                   OpenCB->ProcessId, OpenCB->Identifier,
3132                                   userp, &req, &ldp);
3133             if (code == 0)
3134                 code = RDR_CheckAccess(scp, userp, &req, OpenCB->DesiredAccess, &pResultCB->GrantedAccess);
3135
3136
3137             cm_CheckNTOpenDone(scp, userp, &req, &ldp);
3138         } while (count < 100 && (code == CM_ERROR_RETRY || code == CM_ERROR_WOULDBLOCK));
3139     }
3140
3141     /*
3142      * If we are restricting sharing, we should do so with a suitable
3143      * share lock.
3144      */
3145     if (code == 0 && scp->fileType == CM_SCACHETYPE_FILE && !(OpenCB->ShareAccess & FILE_SHARE_WRITE)) {
3146         cm_key_t key;
3147         LARGE_INTEGER LOffset, LLength;
3148         int sLockType;
3149
3150         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
3151         LOffset.LowPart = SMB_FID_QLOCK_LOW;
3152         LLength.HighPart = 0;
3153         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
3154
3155         /*
3156          * If we are not opening the file for writing, then we don't
3157          * try to get an exclusive lock.  No one else should be able to
3158          * get an exclusive lock on the file anyway, although someone
3159          * else can get a shared lock.
3160          */
3161         if ((OpenCB->ShareAccess & FILE_SHARE_READ) || !(OpenCB->DesiredAccess & AFS_ACCESS_WRITE))
3162         {
3163             sLockType = LOCKING_ANDX_SHARED_LOCK;
3164         } else {
3165             sLockType = 0;
3166         }
3167
3168         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, OpenCB->Identifier);
3169
3170         lock_ObtainWrite(&scp->rw);
3171         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, &req, NULL);
3172         lock_ReleaseWrite(&scp->rw);
3173
3174         if (code) {
3175             code = CM_ERROR_SHARING_VIOLATION;
3176             pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3177         } else {
3178             if (sLockType == LOCKING_ANDX_SHARED_LOCK)
3179                 pResultCB->FileAccess = AFS_FILE_ACCESS_SHARED;
3180             else
3181                 pResultCB->FileAccess = AFS_FILE_ACCESS_EXCLUSIVE;
3182         }
3183     } else {
3184         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3185     }
3186
3187     cm_ReleaseUser(sysUserp);
3188     if (code == 0 && bHoldFid)
3189         RDR_FlagScpInUse( scp, FALSE );
3190     cm_ReleaseSCache(scp);
3191
3192     if (code) {
3193         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3194         (*ResultCB)->ResultStatus = status;
3195         osi_Log2(afsd_logp, "RDR_OpenFileEntry FAILURE code=0x%x status=0x%x",
3196                   code, status);
3197     } else {
3198         (*ResultCB)->ResultStatus = 0;
3199         (*ResultCB)->ResultBufferLength = sizeof( AFSFileOpenResultCB);
3200         osi_Log0(afsd_logp, "RDR_OpenFileEntry SUCCESS");
3201     }
3202     return;
3203 }
3204
3205 void
3206 RDR_ReleaseFileAccess( IN cm_user_t *userp,
3207                        IN AFSFileID FileId,
3208                        IN AFSFileAccessReleaseCB *ReleaseFileCB,
3209                        IN BOOL bWow64,
3210                        IN DWORD ResultBufferLength,
3211                        IN OUT AFSCommResult **ResultCB)
3212 {
3213     cm_key_t key;
3214     unsigned int sLockType;
3215     LARGE_INTEGER LOffset, LLength;
3216     cm_scache_t *scp = NULL;
3217     cm_fid_t    Fid;
3218     afs_uint32  code;
3219     cm_req_t    req;
3220     DWORD       status;
3221
3222     RDR_InitReq(&req, bWow64);
3223
3224     osi_Log4(afsd_logp, "RDR_ReleaseFileAccess File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3225               FileId.Cell, FileId.Volume,
3226               FileId.Vnode, FileId.Unique);
3227
3228     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
3229     if (!(*ResultCB)) {
3230         osi_Log0(afsd_logp, "RDR_ReleaseFileAccess out of memory");
3231         return;
3232     }
3233
3234     memset( *ResultCB, '\0', sizeof( AFSCommResult));
3235
3236     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_NOLOCK)
3237         return;
3238
3239     /* Process the release */
3240     Fid.cell = FileId.Cell;
3241     Fid.volume = FileId.Volume;
3242     Fid.vnode = FileId.Vnode;
3243     Fid.unique = FileId.Unique;
3244     Fid.hash = FileId.Hash;
3245
3246     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3247     if (code) {
3248         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3249         (*ResultCB)->ResultStatus = status;
3250         osi_Log2(afsd_logp, "RDR_ReleaseFileAccess cm_GetSCache FID failure code=0x%x status=0x%x",
3251                   code, status);
3252         return;
3253     }
3254
3255     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_SHARED)
3256         sLockType = LOCKING_ANDX_SHARED_LOCK;
3257     else
3258         sLockType = 0;
3259
3260     key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, ReleaseFileCB->Identifier);
3261
3262     LOffset.HighPart = SMB_FID_QLOCK_HIGH;
3263     LOffset.LowPart = SMB_FID_QLOCK_LOW;
3264     LLength.HighPart = 0;
3265     LLength.LowPart = SMB_FID_QLOCK_LENGTH;
3266
3267     lock_ObtainWrite(&scp->rw);
3268
3269     code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
3270     if (code == 0)
3271     {
3272         code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
3273
3274         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
3275
3276         if (code == CM_ERROR_RANGE_NOT_LOCKED)
3277         {
3278             osi_Log3(afsd_logp, "RDR_ReleaseFileAccess Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
3279                      ReleaseFileCB->FileAccess, ReleaseFileCB->ProcessId, ReleaseFileCB->Identifier);
3280         }
3281     }
3282
3283     lock_ReleaseWrite(&scp->rw);
3284
3285     osi_Log0(afsd_logp, "RDR_ReleaseFileAccessEntry SUCCESS");
3286 }
3287
3288 static const char *
3289 HexCheckSum(unsigned char * buf, int buflen, unsigned char * md5cksum)
3290 {
3291     int i, k;
3292     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
3293
3294     if (buflen < 33)
3295         return "buffer length too small to HexCheckSum";
3296
3297     for (i=0;i<16;i++) {
3298         k = md5cksum[i];
3299
3300         buf[i*2] = tr[k / 16];
3301         buf[i*2+1] = tr[k % 16];
3302     }
3303     buf[32] = '\0';
3304
3305     return buf;
3306 }
3307
3308 /*
3309  * Extent requests from the file system are triggered when a file
3310  * page is not resident in the Windows cache.  The file system is
3311  * responsible for loading the page but cannot block the request
3312  * while doing so.  The AFS Redirector forwards the requests to
3313  * the AFS cache manager while indicating to Windows that the page
3314  * is not yet available.  A polling operation will then ensue with
3315  * the AFS Redirector issuing a RDR_RequestFileExtentsXXX call for
3316  * each poll attempt.  As each request is received and processed
3317  * by a separate worker thread in the service, this can lead to
3318  * contention by multiple threads attempting to claim the same
3319  * cm_buf_t objects.  Therefore, it is important that
3320  *
3321  *  (a) the service avoid processing more than one overlapping
3322  *      extent request at a time
3323  *  (b) background daemon processing be used to avoid blocking
3324  *      of ioctl threads
3325  *
3326  * Beginning with the 20091122 build of the redirector, the redirector
3327  * will not issue an additional RDR_RequestFileExtentsXXX call for