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