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