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