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