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