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