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