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