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