Windows: Enforce Share Access
[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 (scp->redirBufCount > 0) {
1738         LARGE_INTEGER heldExtents;
1739         AFSFileExtentCB extentList[1024];
1740         DWORD extentCount = 0;
1741         cm_buf_t *srbp;
1742         time_t now;
1743
1744         time(&now);
1745         heldExtents.QuadPart = 0;
1746
1747         for ( srbp = redirq_to_cm_buf_t(scp->redirQueueT);
1748               srbp;
1749               srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1750         {
1751             extentList[extentCount].Flags = 0;
1752             extentList[extentCount].Length = cm_data.blockSize;
1753             extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1754             extentList[extentCount].CacheOffset.QuadPart = srbp->datap - RDR_extentBaseAddress;
1755             lock_ObtainWrite(&buf_globalLock);
1756             srbp->redirReleaseRequested = now;
1757             lock_ReleaseWrite(&buf_globalLock);
1758             extentCount++;
1759
1760             if (extentCount == 1024) {
1761                 lock_ReleaseWrite(&scp->rw);
1762                 code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1763                 if (code) {
1764                     if (code == CM_ERROR_RETRY) {
1765                         /*
1766                          * The redirector either is not holding the extents or cannot let them
1767                          * go because they are otherwise in use.  At the moment, do nothing.
1768                          */
1769                     } else
1770                         break;
1771                 }
1772                 extentCount = 0;
1773                 bFlushFile = TRUE;
1774                 lock_ObtainWrite(&scp->rw);
1775             }
1776         }
1777
1778         if (code == 0 && extentCount > 0) {
1779             if (bScpLocked) {
1780                 lock_ReleaseWrite(&scp->rw);
1781                 bScpLocked = FALSE;
1782             }
1783             code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1784             bFlushFile = TRUE;
1785         }
1786     }
1787
1788     /* No longer in use by redirector */
1789     if (!bScpLocked) {
1790         lock_ObtainWrite(&scp->rw);
1791         bScpLocked = TRUE;
1792     }
1793
1794     if (bLastHandle) {
1795         lock_AssertWrite(&scp->rw);
1796         scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
1797     }
1798
1799     if (bLastHandle || bFlushFile) {
1800         if (bScpLocked) {
1801             lock_ReleaseWrite(&scp->rw);
1802             bScpLocked = FALSE;
1803         }
1804         code = buf_CleanVnode(scp, userp, &req);
1805         if (bLastHandle && code)
1806             goto on_error;
1807     }
1808
1809     if (bUnlockFile || bDeleteFile) {
1810         if (!bScpLocked) {
1811             lock_ObtainWrite(&scp->rw);
1812             bScpLocked = TRUE;
1813         }
1814         code = cm_SyncOp(scp, NULL, userp, &req, 0,
1815                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1816         if (code) {
1817             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp (2) failure scp=0x%p code=0x%x",
1818                      scp, code);
1819             goto on_error;
1820         }
1821
1822         key = cm_GenerateKey(CM_SESSION_IFS, CleanupCB->ProcessId, 0);
1823
1824         /* the scp is now locked and current */
1825         code = cm_UnlockByKey(scp, key,
1826                               bDeleteFile ? CM_UNLOCK_FLAG_BY_FID : 0,
1827                               userp, &req);
1828
1829         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1830
1831         if (code)
1832             goto on_error;
1833     }
1834
1835     if (CleanupCB->ChangeTime.QuadPart) {
1836
1837         if (scp->fileType == CM_SCACHETYPE_FILE) {
1838             /* Do not set length and other attributes at the same time */
1839             if (scp->length.QuadPart != CleanupCB->AllocationSize.QuadPart) {
1840                 osi_Log2(afsd_logp, "RDR_CleanupFileEntry Length Change 0x%x -> 0x%x",
1841                           (afs_uint32)scp->length.QuadPart, (afs_uint32)CleanupCB->AllocationSize.QuadPart);
1842                 setAttr.mask |= CM_ATTRMASK_LENGTH;
1843                 setAttr.length.LowPart = CleanupCB->AllocationSize.LowPart;
1844                 setAttr.length.HighPart = CleanupCB->AllocationSize.HighPart;
1845
1846                 if (bScpLocked) {
1847                     lock_ReleaseWrite(&scp->rw);
1848                     bScpLocked = FALSE;
1849                 }
1850                 code = cm_SetAttr(scp, &setAttr, userp, &req);
1851                 if (code)
1852                     goto on_error;
1853                 setAttr.mask = 0;
1854             }
1855         }
1856
1857         if (!bScpLocked) {
1858             lock_ObtainWrite(&scp->rw);
1859             bScpLocked = TRUE;
1860         }
1861
1862         if ((scp->unixModeBits & 0200) && (CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1863             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1864             setAttr.unixModeBits = scp->unixModeBits & ~0222;
1865         } else if (!(scp->unixModeBits & 0200) && !(CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1866             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1867             setAttr.unixModeBits = scp->unixModeBits | 0222;
1868         }
1869     }
1870
1871     if (CleanupCB->LastWriteTime.QuadPart) {
1872         ft.dwLowDateTime = CleanupCB->LastWriteTime.LowPart;
1873         ft.dwHighDateTime = CleanupCB->LastWriteTime.HighPart;
1874
1875         cm_UnixTimeFromLargeSearchTime(&clientModTime, &ft);
1876         if (scp->clientModTime != clientModTime) {
1877             setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1878             setAttr.clientModTime = clientModTime;
1879         }
1880     }
1881
1882     /* call setattr */
1883     if (setAttr.mask) {
1884         lock_ReleaseWrite(&scp->rw);
1885         bScpLocked = FALSE;
1886         code = cm_SetAttr(scp, &setAttr, userp, &req);
1887     } else
1888         code = 0;
1889
1890     /* Now drop the lock enforcing the share access */
1891     if ( CleanupCB->FileAccess != AFS_FILE_ACCESS_NOLOCK) {
1892         unsigned int sLockType;
1893         LARGE_INTEGER LOffset, LLength;
1894
1895         if (CleanupCB->FileAccess == AFS_FILE_ACCESS_SHARED)
1896             sLockType = LOCKING_ANDX_SHARED_LOCK;
1897         else
1898             sLockType = 0;
1899
1900         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, CleanupCB->Identifier);
1901
1902         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
1903         LOffset.LowPart = SMB_FID_QLOCK_LOW;
1904         LLength.HighPart = 0;
1905         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
1906
1907         if (!bScpLocked) {
1908             lock_ObtainWrite(&scp->rw);
1909             bScpLocked = TRUE;
1910         }
1911
1912         code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
1913         if (code == 0)
1914         {
1915             code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
1916
1917             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
1918
1919             if (code == CM_ERROR_RANGE_NOT_LOCKED)
1920             {
1921                 osi_Log3(afsd_logp, "RDR_CleanupFileEntry Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
1922                          CleanupCB->FileAccess, CleanupCB->ProcessId, CleanupCB->Identifier);
1923
1924             }
1925         }
1926     }
1927
1928   on_error:
1929     if (bDscpLocked)
1930         lock_ReleaseWrite(&dscp->rw);
1931     if (bScpLocked)
1932         lock_ReleaseWrite(&scp->rw);
1933
1934     if (dscp && bDeleteFile) {
1935         WCHAR FileName[260];
1936
1937         StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1938
1939         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
1940             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
1941         else
1942             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
1943     }
1944
1945     if (code == 0) {
1946         (*ResultCB)->ResultStatus = 0;
1947         (*ResultCB)->ResultBufferLength = 0;
1948         osi_Log0(afsd_logp, "RDR_CleanupFileEntry SUCCESS");
1949     } else {
1950         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1951         (*ResultCB)->ResultStatus = status;
1952         (*ResultCB)->ResultBufferLength = 0;
1953         osi_Log2(afsd_logp, "RDR_CleanupFileEntry FAILURE code=0x%x status=0x%x",
1954                   code, status);
1955     }
1956     if (scp)
1957         cm_ReleaseSCache(scp);
1958     if (dscp)
1959         cm_ReleaseSCache(dscp);
1960
1961     return;
1962 }
1963
1964 void
1965 RDR_DeleteFileEntry( IN cm_user_t *userp,
1966                      IN AFSFileID ParentId,
1967                      IN ULONGLONG ProcessId,
1968                      IN WCHAR *FileNameCounted,
1969                      IN DWORD FileNameLength,
1970                      IN BOOL bWow64,
1971                      IN BOOL bCheckOnly,
1972                      IN DWORD ResultBufferLength,
1973                      IN OUT AFSCommResult **ResultCB)
1974 {
1975
1976     AFSFileDeleteResultCB *pResultCB = NULL;
1977     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1978     cm_fid_t            parentFid;
1979     afs_uint32          code;
1980     cm_scache_t *       dscp = NULL;
1981     cm_scache_t *       scp = NULL;
1982     afs_uint32          flags = 0;
1983     cm_attr_t           setAttr;
1984     cm_req_t            req;
1985     DWORD               status;
1986     wchar_t             FileName[260];
1987     cm_key_t            key;
1988
1989     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1990
1991     osi_Log4(afsd_logp, "RDR_DeleteFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1992               ParentId.Cell,  ParentId.Volume,
1993               ParentId.Vnode, ParentId.Unique);
1994     osi_Log2(afsd_logp, "... name=%S checkOnly=%x",
1995              osi_LogSaveStringW(afsd_logp, FileName),
1996              bCheckOnly);
1997
1998     RDR_InitReq(&req);
1999     if ( bWow64 )
2000         req.flags |= CM_REQ_WOW64;
2001     memset(&setAttr, 0, sizeof(cm_attr_t));
2002
2003     *ResultCB = (AFSCommResult *)malloc( size);
2004     if (!(*ResultCB)) {
2005         osi_Log0(afsd_logp, "RDR_DeleteFileEntry out of memory");
2006         return;
2007     }
2008
2009     memset( *ResultCB,
2010             '\0',
2011             size);
2012
2013     parentFid.cell   = ParentId.Cell;
2014     parentFid.volume = ParentId.Volume;
2015     parentFid.vnode  = ParentId.Vnode;
2016     parentFid.unique = ParentId.Unique;
2017     parentFid.hash   = ParentId.Hash;
2018
2019     code = cm_GetSCache(&parentFid, &dscp, userp, &req);
2020     if (code) {
2021         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2022         (*ResultCB)->ResultStatus = status;
2023         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
2024                   code, status);
2025         return;
2026     }
2027
2028     lock_ObtainWrite(&dscp->rw);
2029
2030     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
2031                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2032     if (code) {
2033         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2034         (*ResultCB)->ResultStatus = status;
2035         (*ResultCB)->ResultBufferLength = 0;
2036         lock_ReleaseWrite(&dscp->rw);
2037         cm_ReleaseSCache(dscp);
2038         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
2039                  dscp, code, status);
2040         return;
2041     }
2042
2043     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2044     lock_ReleaseWrite(&dscp->rw);
2045
2046     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2047         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2048         cm_ReleaseSCache(dscp);
2049         osi_Log1(afsd_logp, "RDR_DeleteFileEntry Not a Directory dscp=0x%p",
2050                  dscp);
2051         return;
2052     }
2053
2054     code = cm_Lookup(dscp, FileName, 0, userp, &req, &scp);
2055     if (code) {
2056         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2057         (*ResultCB)->ResultStatus = status;
2058         (*ResultCB)->ResultBufferLength = 0;
2059         cm_ReleaseSCache(dscp);
2060         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_Lookup failure code=0x%x status=0x%x",
2061                  code, status);
2062         return;
2063     }
2064
2065     lock_ObtainWrite(&scp->rw);
2066     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_DELETE,
2067                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2068     if (code) {
2069         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2070         (*ResultCB)->ResultStatus = status;
2071         (*ResultCB)->ResultBufferLength = 0;
2072         lock_ReleaseWrite(&scp->rw);
2073         cm_ReleaseSCache(scp);
2074         cm_ReleaseSCache(dscp);
2075         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2076                  scp, code, status);
2077         return;
2078     }
2079
2080     if (!bCheckOnly) {
2081         /* Drop all locks since the file is being deleted */
2082         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2083                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2084         if (code) {
2085             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2086             (*ResultCB)->ResultStatus = status;
2087             (*ResultCB)->ResultBufferLength = 0;
2088             lock_ReleaseWrite(&scp->rw);
2089             cm_ReleaseSCache(scp);
2090             cm_ReleaseSCache(dscp);
2091             osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp Lock failure scp=0x%p code=0x%x status=0x%x",
2092                      scp, code, status);
2093         }
2094
2095         /* the scp is now locked and current */
2096         key = cm_GenerateKey(CM_SESSION_IFS, ProcessId, 0);
2097
2098         code = cm_UnlockByKey(scp, key,
2099                               CM_UNLOCK_FLAG_BY_FID,
2100                               userp, &req);
2101
2102         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2103         lock_ReleaseWrite(&scp->rw);
2104
2105         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2106             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2107         else
2108             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2109     } else {
2110         lock_ReleaseWrite(&scp->rw);
2111     }
2112
2113     if (code == 0) {
2114         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
2115
2116         (*ResultCB)->ResultBufferLength = sizeof( AFSFileDeleteResultCB);
2117
2118         pResultCB = (AFSFileDeleteResultCB *)(*ResultCB)->ResultData;
2119
2120         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
2121         osi_Log0(afsd_logp, "RDR_DeleteFileEntry SUCCESS");
2122     } else {
2123         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2124         (*ResultCB)->ResultStatus = status;
2125         (*ResultCB)->ResultBufferLength = 0;
2126         osi_Log2(afsd_logp, "RDR_DeleteFileEntry FAILURE code=0x%x status=0x%x",
2127                   code, status);
2128     }
2129
2130     cm_ReleaseSCache(dscp);
2131     cm_ReleaseSCache(scp);
2132
2133     return;
2134 }
2135
2136 void
2137 RDR_RenameFileEntry( IN cm_user_t *userp,
2138                      IN WCHAR    *SourceFileNameCounted,
2139                      IN DWORD     SourceFileNameLength,
2140                      IN AFSFileID SourceFileId,
2141                      IN AFSFileRenameCB *pRenameCB,
2142                      IN BOOL bWow64,
2143                      IN DWORD ResultBufferLength,
2144                      IN OUT AFSCommResult **ResultCB)
2145 {
2146
2147     AFSFileRenameResultCB *pResultCB = NULL;
2148     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2149     AFSFileID              SourceParentId   = pRenameCB->SourceParentId;
2150     AFSFileID              TargetParentId   = pRenameCB->TargetParentId;
2151     WCHAR *                TargetFileNameCounted = pRenameCB->TargetName;
2152     DWORD                  TargetFileNameLength = pRenameCB->TargetNameLength;
2153     cm_fid_t               SourceParentFid;
2154     cm_fid_t               TargetParentFid;
2155     cm_scache_t *          oldDscp;
2156     cm_scache_t *          newDscp;
2157     wchar_t                shortName[13];
2158     wchar_t                SourceFileName[260];
2159     wchar_t                TargetFileName[260];
2160     cm_dirFid_t            dfid;
2161     cm_req_t               req;
2162     afs_uint32             code;
2163     DWORD                  status;
2164
2165     RDR_InitReq(&req);
2166     if ( bWow64 )
2167         req.flags |= CM_REQ_WOW64;
2168
2169     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2170     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2171
2172     osi_Log4(afsd_logp, "RDR_RenameFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2173               SourceParentId.Cell,  SourceParentId.Volume,
2174               SourceParentId.Vnode, SourceParentId.Unique);
2175     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2176     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2177               TargetParentId.Cell,  TargetParentId.Volume,
2178               TargetParentId.Vnode, TargetParentId.Unique);
2179     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2180
2181     *ResultCB = (AFSCommResult *)malloc( size);
2182     if (!(*ResultCB))
2183         return;
2184
2185     memset( *ResultCB,
2186             '\0',
2187             size);
2188
2189     pResultCB = (AFSFileRenameResultCB *)(*ResultCB)->ResultData;
2190
2191     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2192     {
2193         osi_Log2(afsd_logp, "RDR_RenameFileEntry Invalid Name Length: src %u target %u",
2194                  SourceFileNameLength, TargetFileNameLength);
2195         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2196         return;
2197     }
2198
2199     SourceParentFid.cell   = SourceParentId.Cell;
2200     SourceParentFid.volume = SourceParentId.Volume;
2201     SourceParentFid.vnode  = SourceParentId.Vnode;
2202     SourceParentFid.unique = SourceParentId.Unique;
2203     SourceParentFid.hash   = SourceParentId.Hash;
2204
2205     TargetParentFid.cell   = TargetParentId.Cell;
2206     TargetParentFid.volume = TargetParentId.Volume;
2207     TargetParentFid.vnode  = TargetParentId.Vnode;
2208     TargetParentFid.unique = TargetParentId.Unique;
2209     TargetParentFid.hash   = TargetParentId.Hash;
2210
2211     code = cm_GetSCache(&SourceParentFid, &oldDscp, userp, &req);
2212     if (code) {
2213         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache source parent failed code 0x%x", code);
2214         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2215         (*ResultCB)->ResultStatus = status;
2216         return;
2217     }
2218
2219     lock_ObtainWrite(&oldDscp->rw);
2220     code = cm_SyncOp(oldDscp, NULL, userp, &req, 0,
2221                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2222     if (code) {
2223         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp oldDscp 0x%p failed code 0x%x", oldDscp, code);
2224         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2225         (*ResultCB)->ResultStatus = status;
2226         lock_ReleaseWrite(&oldDscp->rw);
2227         cm_ReleaseSCache(oldDscp);
2228         return;
2229     }
2230
2231     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2232     lock_ReleaseWrite(&oldDscp->rw);
2233
2234
2235     if (oldDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2236         osi_Log1(afsd_logp, "RDR_RenameFileEntry oldDscp 0x%p not a directory", oldDscp);
2237         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2238         cm_ReleaseSCache(oldDscp);
2239         return;
2240     }
2241
2242     code = cm_GetSCache(&TargetParentFid, &newDscp, userp, &req);
2243     if (code) {
2244         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target parent failed code 0x%x", code);
2245         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2246         (*ResultCB)->ResultStatus = status;
2247         cm_ReleaseSCache(oldDscp);
2248         return;
2249     }
2250
2251     lock_ObtainWrite(&newDscp->rw);
2252     code = cm_SyncOp(newDscp, NULL, userp, &req, 0,
2253                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2254     if (code) {
2255         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp newDscp 0x%p failed code 0x%x", newDscp, code);
2256         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2257         (*ResultCB)->ResultStatus = status;
2258         lock_ReleaseWrite(&newDscp->rw);
2259         cm_ReleaseSCache(oldDscp);
2260         cm_ReleaseSCache(newDscp);
2261         return;
2262     }
2263
2264     cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2265     lock_ReleaseWrite(&newDscp->rw);
2266
2267
2268     if (newDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2269         osi_Log1(afsd_logp, "RDR_RenameFileEntry newDscp 0x%p not a directory", newDscp);
2270         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2271         cm_ReleaseSCache(oldDscp);
2272         cm_ReleaseSCache(newDscp);
2273         return;
2274     }
2275
2276     code = cm_Rename( oldDscp, NULL, SourceFileName,
2277                       newDscp, TargetFileName, userp, &req);
2278     if (code == 0) {
2279         cm_dirOp_t dirop;
2280         cm_fid_t   targetFid;
2281         cm_scache_t *scp = 0;
2282         DWORD dwRemaining;
2283
2284         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2285         dwRemaining = ResultBufferLength - sizeof( AFSFileRenameResultCB) + sizeof( AFSDirEnumEntry);
2286         (*ResultCB)->ResultStatus = 0;
2287
2288         pResultCB->SourceParentDataVersion.QuadPart = oldDscp->dataVersion;
2289         pResultCB->TargetParentDataVersion.QuadPart = newDscp->dataVersion;
2290
2291         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p SUCCESS",
2292                  oldDscp, newDscp);
2293
2294         code = cm_BeginDirOp( newDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2295         if (code == 0) {
2296             code = cm_BPlusDirLookup(&dirop, TargetFileName, &targetFid);
2297             cm_EndDirOp(&dirop);
2298         }
2299
2300         if (code != 0) {
2301             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_BPlusDirLookup failed code 0x%x",
2302                      code);
2303             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2304             cm_ReleaseSCache(oldDscp);
2305             cm_ReleaseSCache(newDscp);
2306             return;
2307         }
2308
2309         osi_Log4(afsd_logp, "RDR_RenameFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2310                   targetFid.cell,  targetFid.volume,
2311                   targetFid.vnode, targetFid.unique);
2312
2313         code = cm_GetSCache(&targetFid, &scp, userp, &req);
2314         if (code) {
2315             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target failed code 0x%x", code);
2316             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2317             (*ResultCB)->ResultStatus = status;
2318             cm_ReleaseSCache(oldDscp);
2319             cm_ReleaseSCache(newDscp);
2320             return;
2321         }
2322
2323         /* Make sure the source vnode is current */
2324         lock_ObtainWrite(&scp->rw);
2325         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2326                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2327         if (code) {
2328             osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp scp 0x%p failed code 0x%x", scp, code);
2329             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2330             (*ResultCB)->ResultStatus = status;
2331             lock_ReleaseWrite(&scp->rw);
2332             cm_ReleaseSCache(oldDscp);
2333             cm_ReleaseSCache(newDscp);
2334             cm_ReleaseSCache(scp);
2335             return;
2336         }
2337
2338         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2339         lock_ReleaseWrite(&scp->rw);
2340
2341         dfid.vnode = htonl(scp->fid.vnode);
2342         dfid.unique = htonl(scp->fid.unique);
2343
2344         if (!cm_Is8Dot3(TargetFileName))
2345             cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2346         else
2347             shortName[0] = '\0';
2348
2349         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2350                                  newDscp, scp, userp, &req, TargetFileName, shortName,
2351                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2352                                  NULL, &dwRemaining);
2353         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2354         cm_ReleaseSCache(scp);
2355
2356         osi_Log0(afsd_logp, "RDR_RenameFileEntry SUCCESS");
2357     } else {
2358         osi_Log3(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p failed code 0x%x",
2359                  oldDscp, newDscp, code);
2360         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2361         (*ResultCB)->ResultStatus = status;
2362         (*ResultCB)->ResultBufferLength = 0;
2363     }
2364
2365     cm_ReleaseSCache(oldDscp);
2366     cm_ReleaseSCache(newDscp);
2367     return;
2368 }
2369
2370 void
2371 RDR_FlushFileEntry( IN cm_user_t *userp,
2372                     IN AFSFileID FileId,
2373                     IN BOOL bWow64,
2374                     IN DWORD ResultBufferLength,
2375                     IN OUT AFSCommResult **ResultCB)
2376 {
2377     cm_scache_t *scp = NULL;
2378     cm_fid_t    Fid;
2379     afs_uint32  code;
2380     cm_req_t    req;
2381     DWORD       status;
2382 #ifdef ODS_DEBUG
2383     char        dbgstr[1024];
2384 #endif
2385
2386     RDR_InitReq(&req);
2387     if ( bWow64 )
2388         req.flags |= CM_REQ_WOW64;
2389
2390     osi_Log4(afsd_logp, "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x",
2391               FileId.Cell, FileId.Volume,
2392               FileId.Vnode, FileId.Unique);
2393 #ifdef ODS_DEBUG
2394     snprintf( dbgstr, 1024,
2395               "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x\n",
2396               FileId.Cell, FileId.Volume,
2397               FileId.Vnode, FileId.Unique);
2398     OutputDebugStringA( dbgstr);
2399 #endif
2400
2401     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2402     if (!(*ResultCB)) {
2403         osi_Log0(afsd_logp, "RDR_FlushFileEntry out of memory");
2404         return;
2405     }
2406
2407     memset( *ResultCB,
2408             '\0',
2409             sizeof( AFSCommResult));
2410
2411     /* Process the release */
2412     Fid.cell = FileId.Cell;
2413     Fid.volume = FileId.Volume;
2414     Fid.vnode = FileId.Vnode;
2415     Fid.unique = FileId.Unique;
2416     Fid.hash = FileId.Hash;
2417
2418     code = cm_GetSCache(&Fid, &scp, userp, &req);
2419     if (code) {
2420         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2421         (*ResultCB)->ResultStatus = status;
2422         osi_Log2(afsd_logp, "RDR_FlushFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2423                   code, status);
2424         return;
2425     }
2426
2427     lock_ObtainWrite(&scp->rw);
2428     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2429         lock_ReleaseWrite(&scp->rw);
2430         (*ResultCB)->ResultStatus = STATUS_INVALID_HANDLE;
2431         return;
2432     }
2433
2434     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2435                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2436     if (code) {
2437         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2438         (*ResultCB)->ResultStatus = status;
2439         lock_ReleaseWrite(&scp->rw);
2440         cm_ReleaseSCache(scp);
2441         osi_Log3(afsd_logp, "RDR_FlushFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2442                  scp, code, status);
2443         return;
2444     }
2445
2446     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2447     lock_ReleaseWrite(&scp->rw);
2448
2449     code = cm_FSync(scp, userp, &req, FALSE);
2450     cm_ReleaseSCache(scp);
2451
2452     if (code) {
2453         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2454         (*ResultCB)->ResultStatus = status;
2455         osi_Log2(afsd_logp, "RDR_FlushFileEntry FAILURE code=0x%x status=0x%x",
2456                   code, status);
2457     } else {
2458         (*ResultCB)->ResultStatus = 0;
2459         osi_Log0(afsd_logp, "RDR_FlushFileEntry SUCCESS");
2460     }
2461     (*ResultCB)->ResultBufferLength = 0;
2462
2463     return;
2464 }
2465
2466 afs_uint32
2467 RDR_CheckAccess( IN cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
2468                  ULONG access,
2469                  ULONG *granted)
2470 {
2471     ULONG afs_acc, afs_gr;
2472     BOOLEAN file, dir;
2473     afs_uint32 code = 0;
2474
2475     file = (scp->fileType == CM_SCACHETYPE_FILE);
2476     dir = !file;
2477
2478     /* access definitions from prs_fs.h */
2479     afs_acc = 0;
2480     if (access & FILE_READ_DATA)
2481         afs_acc |= PRSFS_READ;
2482     if (access & FILE_READ_EA || access & FILE_READ_ATTRIBUTES)
2483         afs_acc |= PRSFS_READ;
2484     if (file && ((access & FILE_WRITE_DATA) || (access & FILE_APPEND_DATA)))
2485         afs_acc |= PRSFS_WRITE;
2486     if (access & FILE_WRITE_EA || access & FILE_WRITE_ATTRIBUTES)
2487         afs_acc |= PRSFS_WRITE;
2488     if (dir && ((access & FILE_ADD_FILE) || (access & FILE_ADD_SUBDIRECTORY)))
2489         afs_acc |= PRSFS_INSERT;
2490     if (dir && (access & FILE_LIST_DIRECTORY))
2491         afs_acc |= PRSFS_LOOKUP;
2492     if (file && (access & FILE_EXECUTE))
2493         afs_acc |= PRSFS_WRITE;
2494     if (dir && (access & FILE_TRAVERSE))
2495         afs_acc |= PRSFS_READ;
2496     if (dir && (access & FILE_DELETE_CHILD))
2497         afs_acc |= PRSFS_DELETE;
2498     if ((access & DELETE))
2499         afs_acc |= PRSFS_DELETE;
2500
2501     /* check ACL with server */
2502     lock_ObtainWrite(&scp->rw);
2503     while (1)
2504     {
2505         if (cm_HaveAccessRights(scp, userp, reqp, afs_acc, &afs_gr))
2506         {
2507             break;
2508         }
2509         else
2510         {
2511             /* we don't know the required access rights */
2512             code = cm_GetAccessRights(scp, userp, reqp);
2513             if (code)
2514                 break;
2515             continue;
2516         }
2517     }
2518     lock_ReleaseWrite(&(scp->rw));
2519
2520     if (code == 0) {
2521         *granted = 0;
2522         if (afs_gr & PRSFS_READ)
2523             *granted |= FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_EXECUTE;
2524         if (afs_gr & PRSFS_WRITE)
2525             *granted |= FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_EXECUTE;
2526         if (afs_gr & PRSFS_INSERT)
2527             *granted |= (dir ? FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY : 0) | (file ? FILE_ADD_SUBDIRECTORY : 0);
2528         if (afs_gr & PRSFS_LOOKUP)
2529             *granted |= (dir ? FILE_LIST_DIRECTORY : 0);
2530         if (afs_gr & PRSFS_DELETE)
2531             *granted |= FILE_DELETE_CHILD | DELETE;
2532         if (afs_gr & PRSFS_LOCK)
2533             *granted |= 0;
2534         if (afs_gr & PRSFS_ADMINISTER)
2535             *granted |= 0;
2536
2537         *granted |= SYNCHRONIZE | READ_CONTROL;
2538
2539         /* don't give more access than what was requested */
2540         *granted &= access;
2541         osi_Log3(afsd_logp, "RDR_CheckAccess SUCCESS scp=0x%p requested=0x%x granted=0x%x", scp, access, *granted);
2542     } else
2543         osi_Log2(afsd_logp, "RDR_CheckAccess FAILURE scp=0x%p code=0x%x",
2544                  scp, code);
2545
2546     return code;
2547 }
2548
2549 void
2550 RDR_OpenFileEntry( IN cm_user_t *userp,
2551                    IN AFSFileID FileId,
2552                    IN AFSFileOpenCB *OpenCB,
2553                    IN BOOL bWow64,
2554                    IN BOOL bHoldFid,
2555                    IN DWORD ResultBufferLength,
2556                    IN OUT AFSCommResult **ResultCB)
2557 {
2558     AFSFileOpenResultCB *pResultCB = NULL;
2559     cm_scache_t *scp = NULL;
2560     cm_user_t   *sysUserp = NULL;
2561     cm_fid_t    Fid;
2562     cm_lock_data_t      *ldp = NULL;
2563     afs_uint32  code;
2564     cm_req_t    req;
2565     DWORD       status;
2566
2567     RDR_InitReq(&req);
2568     if ( bWow64 )
2569         req.flags |= CM_REQ_WOW64;
2570
2571     osi_Log4(afsd_logp, "RDR_OpenFileEntry File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2572               FileId.Cell, FileId.Volume,
2573               FileId.Vnode, FileId.Unique);
2574
2575     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2576     if (!(*ResultCB)) {
2577         osi_Log0(afsd_logp, "RDR_OpenFileEntry out of memory");
2578         return;
2579     }
2580
2581     memset( *ResultCB,
2582             '\0',
2583             sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2584
2585     pResultCB = (AFSFileOpenResultCB *)(*ResultCB)->ResultData;
2586
2587     /* Process the release */
2588     Fid.cell = FileId.Cell;
2589     Fid.volume = FileId.Volume;
2590     Fid.vnode = FileId.Vnode;
2591     Fid.unique = FileId.Unique;
2592     Fid.hash = FileId.Hash;
2593
2594     code = cm_GetSCache(&Fid, &scp, userp, &req);
2595     if (code) {
2596         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2597         (*ResultCB)->ResultStatus = status;
2598         osi_Log2(afsd_logp, "RDR_OpenFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2599                   code, status);
2600         return;
2601     }
2602
2603     lock_ObtainWrite(&scp->rw);
2604     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2605                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2606     if (code) {
2607         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2608         (*ResultCB)->ResultStatus = status;
2609         lock_ReleaseWrite(&scp->rw);
2610         cm_ReleaseSCache(scp);
2611         osi_Log3(afsd_logp, "RDR_OpenFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2612                  scp, code, status);
2613         return;
2614     }
2615
2616     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2617     lock_ReleaseWrite(&scp->rw);
2618
2619     sysUserp = RDR_GetLocalSystemUser();
2620
2621     /*
2622      * Skip the open check if the request is coming from the local system account.
2623      * The local system has no tokens and therefore any requests sent to a file
2624      * server will fail.  Unfortunately, there are special system processes that
2625      * perform actions on files and directories in preparation for memory mapping
2626      * executables.  If the open check fails, the real request from the user process
2627      * will never be issued.
2628      *
2629      * Permitting the file system to allow subsequent operations to proceed does
2630      * not compromise security.  All requests to obtain file data or directory
2631      * enumerations will subsequently fail if they are not submitted under the
2632      * context of a process for that have access to the necessary credentials.
2633      */
2634
2635     if ( userp == sysUserp)
2636     {
2637         osi_Log1(afsd_logp, "RDR_OpenFileEntry LOCAL_SYSTEM access check skipped scp=0x%p",
2638                  scp);
2639         pResultCB->GrantedAccess = OpenCB->DesiredAccess;
2640         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2641         code = 0;
2642     }
2643     else
2644     {
2645         int count = 0;
2646
2647         do {
2648             if (count++ > 0) {
2649                 Sleep(350);
2650                 osi_Log3(afsd_logp,
2651                          "RDR_OpenFileEntry repeating open check scp=0x%p userp=0x%p code=0x%x",
2652                          scp, userp, code);
2653             }
2654             code = cm_CheckNTOpen(scp, OpenCB->DesiredAccess, OpenCB->ShareAccess,
2655                                   OPEN_ALWAYS,
2656                                   OpenCB->ProcessId, OpenCB->Identifier,
2657                                   userp, &req, &ldp);
2658             if (code == 0)
2659                 code = RDR_CheckAccess(scp, userp, &req, OpenCB->DesiredAccess, &pResultCB->GrantedAccess);
2660             cm_CheckNTOpenDone(scp, userp, &req, &ldp);
2661         } while (count < 100 && (code == CM_ERROR_RETRY || code == CM_ERROR_WOULDBLOCK));
2662     }
2663
2664     /*
2665      * If we are restricting sharing, we should do so with a suitable
2666      * share lock.
2667      */
2668     if (code == 0 && scp->fileType == CM_SCACHETYPE_FILE && !(OpenCB->ShareAccess & FILE_SHARE_WRITE)) {
2669         cm_key_t key;
2670         LARGE_INTEGER LOffset, LLength;
2671         int sLockType;
2672
2673         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
2674         LOffset.LowPart = SMB_FID_QLOCK_LOW;
2675         LLength.HighPart = 0;
2676         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2677
2678         /*
2679          * If we are not opening the file for writing, then we don't
2680          * try to get an exclusive lock.  No one else should be able to
2681          * get an exclusive lock on the file anyway, although someone
2682          * else can get a shared lock.
2683          */
2684         if ((OpenCB->ShareAccess & FILE_SHARE_READ) || !(OpenCB->DesiredAccess & AFS_ACCESS_WRITE))
2685         {
2686             sLockType = LOCKING_ANDX_SHARED_LOCK;
2687         } else {
2688             sLockType = 0;
2689         }
2690
2691         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, OpenCB->Identifier);
2692
2693         lock_ObtainWrite(&scp->rw);
2694         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, &req, NULL);
2695         lock_ReleaseWrite(&scp->rw);
2696
2697         if (code) {
2698             code = CM_ERROR_SHARING_VIOLATION;
2699             pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2700         } else {
2701             if (sLockType == LOCKING_ANDX_SHARED_LOCK)
2702                 pResultCB->FileAccess = AFS_FILE_ACCESS_SHARED;
2703             else
2704                 pResultCB->FileAccess = AFS_FILE_ACCESS_EXCLUSIVE;
2705         }
2706     } else {
2707         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2708     }
2709
2710     cm_ReleaseUser(sysUserp);
2711     if (code == 0 && bHoldFid)
2712         RDR_FlagScpInUse( scp, FALSE );
2713     cm_ReleaseSCache(scp);
2714
2715     if (code) {
2716         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2717         (*ResultCB)->ResultStatus = status;
2718         osi_Log2(afsd_logp, "RDR_OpenFileEntry FAILURE code=0x%x status=0x%x",
2719                   code, status);
2720     } else {
2721         (*ResultCB)->ResultStatus = 0;
2722         (*ResultCB)->ResultBufferLength = sizeof( AFSFileOpenResultCB);
2723         osi_Log0(afsd_logp, "RDR_OpenFileEntry SUCCESS");
2724     }
2725     return;
2726 }
2727
2728 void
2729 RDR_ReleaseFileAccess( IN cm_user_t *userp,
2730                        IN AFSFileID FileId,
2731                        IN AFSFileAccessReleaseCB *ReleaseFileCB,
2732                        IN BOOL bWow64,
2733                        IN DWORD ResultBufferLength,
2734                        IN OUT AFSCommResult **ResultCB)
2735 {
2736     cm_key_t key;
2737     unsigned int sLockType;
2738     LARGE_INTEGER LOffset, LLength;
2739     cm_scache_t *scp = NULL;
2740     cm_fid_t    Fid;
2741     afs_uint32  code;
2742     cm_req_t    req;
2743     DWORD       status;
2744
2745     RDR_InitReq(&req);
2746     if ( bWow64 )
2747         req.flags |= CM_REQ_WOW64;
2748
2749     osi_Log4(afsd_logp, "RDR_ReleaseFileAccess File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2750               FileId.Cell, FileId.Volume,
2751               FileId.Vnode, FileId.Unique);
2752
2753     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2754     if (!(*ResultCB)) {
2755         osi_Log0(afsd_logp, "RDR_ReleaseFileAccess out of memory");
2756         return;
2757     }
2758
2759     memset( *ResultCB, '\0', sizeof( AFSCommResult));
2760
2761     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_NOLOCK)
2762         return;
2763
2764     /* Process the release */
2765     Fid.cell = FileId.Cell;
2766     Fid.volume = FileId.Volume;
2767     Fid.vnode = FileId.Vnode;
2768     Fid.unique = FileId.Unique;
2769     Fid.hash = FileId.Hash;
2770
2771     code = cm_GetSCache(&Fid, &scp, userp, &req);
2772     if (code) {
2773         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2774         (*ResultCB)->ResultStatus = status;
2775         osi_Log2(afsd_logp, "RDR_ReleaseFileAccess cm_GetSCache FID failure code=0x%x status=0x%x",
2776                   code, status);
2777         return;
2778     }
2779
2780     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_SHARED)
2781         sLockType = LOCKING_ANDX_SHARED_LOCK;
2782     else
2783         sLockType = 0;
2784
2785     key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, ReleaseFileCB->Identifier);
2786
2787     LOffset.HighPart = SMB_FID_QLOCK_HIGH;
2788     LOffset.LowPart = SMB_FID_QLOCK_LOW;
2789     LLength.HighPart = 0;
2790     LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2791
2792     lock_ObtainWrite(&scp->rw);
2793
2794     code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
2795     if (code == 0)
2796     {
2797         code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
2798
2799         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
2800
2801         if (code == CM_ERROR_RANGE_NOT_LOCKED)
2802         {
2803             osi_Log3(afsd_logp, "RDR_ReleaseFileAccess Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
2804                      ReleaseFileCB->FileAccess, ReleaseFileCB->ProcessId, ReleaseFileCB->Identifier);
2805         }
2806     }
2807
2808     lock_ReleaseWrite(&scp->rw);
2809
2810     osi_Log0(afsd_logp, "RDR_ReleaseFileAccessEntry SUCCESS");
2811 }
2812
2813 static const char *
2814 HexCheckSum(unsigned char * buf, int buflen, unsigned char * md5cksum)
2815 {
2816     int i, k;
2817     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
2818
2819     if (buflen < 33)
2820         return "buffer length too small to HexCheckSum";
2821
2822     for (i=0;i<16;i++) {
2823         k = md5cksum[i];
2824
2825         buf[i*2] = tr[k / 16];
2826         buf[i*2+1] = tr[k % 16];
2827     }
2828     buf[32] = '\0';
2829
2830     return buf;
2831 }
2832
2833 /*
2834  * Extent requests from the file system are triggered when a file
2835  * page is not resident in the Windows cache.  The file system is
2836  * responsible for loading the page but cannot block the request
2837  * while doing so.  The AFS Redirector forwards the requests to
2838  * the AFS cache manager while indicating to Windows that the page
2839  * is not yet available.  A polling operation will then ensue with
2840  * the AFS Redirector issuing a RDR_RequestFileExtentsXXX call for
2841  * each poll attempt.  As each request is received and processed
2842  * by a separate worker thread in the service, this can lead to
2843  * contention by multiple threads attempting to claim the same
2844  * cm_buf_t objects.  Therefore, it is important that
2845  *
2846  *  (a) the service avoid processing more than one overlapping
2847  *      extent request at a time
2848  *  (b) background daemon processing be used to avoid blocking
2849  *      of ioctl threads
2850  *
2851  * Beginning with the 20091122 build of the redirector, the redirector
2852  * will not issue an additional RDR_RequestFileExtentsXXX call for
2853  * each poll request.  Instead, afsd_service is required to track
2854  * the requests and return them to the redirector or fail the
2855  * portions of the request that cannot be satisfied.
2856  *
2857  * The request processing returns any extents that can be returned
2858  * immediately to the redirector.  The rest of the requested range(s)
2859  * are queued as background operations using RDR_BkgFetch().
2860  */
2861
2862 /* do the background fetch. */
2863 afs_int32
2864 RDR_BkgFetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
2865              cm_user_t *userp, cm_req_t *reqp)
2866 {
2867     osi_hyper_t length;
2868     osi_hyper_t base;
2869     osi_hyper_t offset;
2870     osi_hyper_t end;
2871     osi_hyper_t fetched;
2872     osi_hyper_t tblocksize;
2873     afs_int32 code;
2874     int rwheld = 0;
2875     cm_buf_t *bufp = NULL;
2876     DWORD dwResultBufferLength;
2877     AFSSetFileExtentsCB *pResultCB;
2878     DWORD status;
2879     afs_uint32 count=0;
2880     AFSFileID FileId;
2881     int reportErrorToRedir = 0;
2882     int force_retry = 0;
2883
2884     FileId.Cell = scp->fid.cell;
2885     FileId.Volume = scp->fid.volume;
2886     FileId.Vnode = scp->fid.vnode;
2887     FileId.Unique = scp->fid.unique;
2888     FileId.Hash = scp->fid.hash;
2889
2890     if ((GetTickCount() - reqp->startTime) / 1000 > HardDeadtimeout * 5) {
2891         RDR_SetFileStatus( &scp->fid, STATUS_IO_TIMEOUT);
2892         return 0;
2893     }
2894
2895     fetched.LowPart = 0;
2896     fetched.HighPart = 0;
2897     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
2898     base.LowPart = p1;
2899     base.HighPart = p2;
2900     length.LowPart = p3;
2901     length.HighPart = p4;
2902
2903     end = LargeIntegerAdd(base, length);
2904
2905     osi_Log5(afsd_logp, "Starting BKG Fetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
2906              scp, p2, p1, p4, p3);
2907
2908     /*
2909      * Make sure we have a callback.
2910      * This is necessary so that we can return access denied
2911      * if a callback cannot be granted.
2912      */
2913     lock_ObtainWrite(&scp->rw);
2914     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_READ,
2915                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2916     if (code) {
2917         lock_ReleaseWrite(&scp->rw);
2918         osi_Log2(afsd_logp, "RDR_BkgFetch cm_SyncOp failure scp=0x%p code=0x%x",
2919                  scp, code);
2920         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
2921         RDR_SetFileStatus( &scp->fid, status);
2922         return code;
2923     }
2924     lock_ReleaseWrite(&scp->rw);
2925
2926     dwResultBufferLength = (DWORD)(sizeof( AFSSetFileExtentsCB) + sizeof( AFSSetFileExtentsCB) * (length.QuadPart / cm_data.blockSize + 1));
2927     pResultCB = (AFSSetFileExtentsCB *)malloc( dwResultBufferLength );
2928     if (!pResultCB)
2929         return CM_ERROR_RETRY;
2930
2931     memset( pResultCB, '\0', dwResultBufferLength );
2932     pResultCB->FileId = FileId;
2933
2934     for ( code = 0, offset = base;
2935           code == 0 && LargeIntegerLessThan(offset, end);
2936           offset = LargeIntegerAdd(offset, tblocksize) )
2937     {
2938         int bBufRelease = TRUE;
2939
2940         if (rwheld) {
2941             lock_ReleaseWrite(&scp->rw);
2942             rwheld = 0;
2943         }
2944
2945         code = buf_Get(scp, &offset, reqp, &bufp);
2946         if (code) {
2947             /*
2948              * any error from buf_Get() is non-fatal.
2949              * we need to re-queue this extent fetch.
2950              */
2951             force_retry = 1;
2952             continue;
2953         }
2954
2955         if (!rwheld) {
2956             lock_ObtainWrite(&scp->rw);
2957             rwheld = 1;
2958         }
2959
2960         code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
2961         if (code == 0) {
2962             if (bufp->flags & CM_BUF_DIRTY) {
2963                 if (rwheld) {
2964                     lock_ReleaseWrite(&scp->rw);
2965                     rwheld = 0;
2966                 }
2967                 cm_BufWrite(scp, &bufp->offset, cm_chunkSize, 0, userp, reqp);
2968             }
2969
2970             if (!(bufp->qFlags & CM_BUF_QREDIR)) {
2971 #ifdef VALIDATE_CHECK_SUM
2972 #ifdef ODS_DEBUG
2973                 char md5dbg[33];
2974                 char dbgstr[1024];
2975 #endif
2976 #endif
2977                 if (!rwheld) {
2978                     lock_ObtainWrite(&scp->rw);
2979                     rwheld = 1;
2980                 }
2981                 lock_ObtainWrite(&buf_globalLock);
2982                 if (!(bufp->flags & CM_BUF_DIRTY) &&
2983                     bufp->cmFlags == 0 &&
2984                     !(bufp->qFlags & CM_BUF_QREDIR)) {
2985                     buf_InsertToRedirQueue(scp, bufp);
2986                     lock_ReleaseWrite(&buf_globalLock);
2987                     lock_ReleaseWrite(&scp->rw);
2988                     rwheld = 0;
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
3034             if (rwheld) {
3035                 lock_ReleaseWrite(&scp->rw);
3036                 rwheld = 0;
3037             }
3038
3039         } else {
3040             /*
3041              * depending on what the error from cm_GetBuffer is
3042              * it may or may not be fatal.  Only return fatal errors.
3043              * Re-queue a request for others.
3044              */
3045             osi_Log5(afsd_logp, "RDR_BkgFetch Extent2FS FAILURE bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x code 0x%x",
3046                       bufp, offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize, code);
3047             switch (code) {
3048             case CM_ERROR_NOACCESS:
3049             case CM_ERROR_NOSUCHFILE:
3050             case CM_ERROR_NOSUCHPATH:
3051             case CM_ERROR_NOSUCHVOLUME:
3052             case CM_ERROR_NOSUCHCELL:
3053             case CM_ERROR_INVAL:
3054             case CM_ERROR_BADFD:
3055             case CM_ERROR_CLOCKSKEW:
3056             case RXKADNOAUTH:
3057             case CM_ERROR_QUOTA:
3058             case CM_ERROR_LOCK_CONFLICT:
3059                 /*
3060                  * these are fatal errors.  deliver what we can
3061                  * and halt.
3062                  */
3063                 reportErrorToRedir = 1;
3064                 break;
3065             default:
3066                 /*
3067                  * non-fatal errors.  re-queue the exent
3068                  */
3069                 code = CM_ERROR_RETRY;
3070             }
3071         }
3072
3073         if (bBufRelease)
3074             buf_Release(bufp);
3075     }
3076
3077     if (!rwheld) {
3078         lock_ObtainWrite(&scp->rw);
3079         rwheld = 1;
3080     }
3081
3082     /* wakeup anyone who is waiting */
3083     if (scp->flags & CM_SCACHEFLAG_WAITING) {
3084         osi_Log1(afsd_logp, "RDR Bkg Fetch Waking scp 0x%p", scp);
3085         osi_Wakeup((LONG_PTR) &scp->flags);
3086     }
3087     lock_ReleaseWrite(&scp->rw);
3088
3089     if (count > 0) {
3090         pResultCB->ExtentCount = count;
3091         RDR_SetFileExtents( pResultCB, dwResultBufferLength);
3092     }
3093     free(pResultCB);
3094
3095     if (reportErrorToRedir) {
3096         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
3097         RDR_SetFileStatus( &scp->fid, status);
3098     }
3099
3100     osi_Log4(afsd_logp, "Ending BKG Fetch scp 0x%p code 0x%x fetched 0x%x:%x",
3101              scp, code, fetched.HighPart, fetched.LowPart);
3102
3103     return force_retry ? CM_ERROR_RETRY : code;
3104 }
3105
3106
3107 BOOL
3108 RDR_RequestFileExtentsAsync( IN cm_user_t *userp,
3109                              IN AFSFileID FileId,
3110                              IN AFSRequestExtentsCB *RequestExtentsCB,
3111                              IN BOOL bWow64,
3112                              IN OUT DWORD * ResultBufferLength,
3113                              IN OUT AFSSetFileExtentsCB **ResultCB)
3114 {
3115     AFSSetFileExtentsCB *pResultCB = NULL;
3116     DWORD Length;
3117     DWORD count;
3118     DWORD status;
3119     cm_scache_t *scp = NULL;
3120     cm_fid_t    Fid;
3121     cm_buf_t    *bufp;
3122     afs_uint32  code = 0;
3123     osi_hyper_t thyper;
3124     LARGE_INTEGER ByteOffset, BeginOffset, EndOffset, QueueOffset;
3125     afs_uint32  QueueLength;
3126     cm_req_t    req;
3127     BOOLEAN     bBufRelease = TRUE;
3128
3129     RDR_InitReq(&req);
3130     if ( bWow64 )
3131         req.flags |= CM_REQ_WOW64;
3132     req.flags |= CM_REQ_NORETRY;
3133
3134     osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3135               FileId.Cell, FileId.Volume,
3136               FileId.Vnode, FileId.Unique);
3137     osi_Log4(afsd_logp, "... Flags 0x%x ByteOffset 0x%x:%x Length 0x%x",
3138              RequestExtentsCB->Flags,
3139              RequestExtentsCB->ByteOffset.HighPart, RequestExtentsCB->ByteOffset.LowPart,
3140              RequestExtentsCB->Length);
3141     Length = sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (RequestExtentsCB->Length / cm_data.blockSize + 1);
3142
3143     pResultCB = *ResultCB = (AFSSetFileExtentsCB *)malloc( Length );
3144     if (*ResultCB == NULL) {
3145         *ResultBufferLength = 0;
3146         return FALSE;
3147     }
3148     *ResultBufferLength = Length;
3149
3150     memset( pResultCB, '\0', Length );
3151     pResultCB->FileId = FileId;
3152
3153     Fid.cell = FileId.Cell;
3154     Fid.volume = FileId.Volume;
3155     Fid.vnode = FileId.Vnode;
3156     Fid.unique = FileId.Unique;
3157     Fid.hash = FileId.Hash;
3158
3159     code = cm_GetSCache(&Fid, &scp, userp, &req);
3160     if (code) {
3161         osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync cm_GetSCache FID failure code=0x%x",
3162                   code);
3163         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3164         RDR_SetFileStatus( &scp->fid, status);
3165         return FALSE;
3166     }
3167
3168     /*
3169      * Make sure we have a callback.
3170      * This is necessary so that we can return access denied
3171      * if a callback cannot be granted.
3172      */
3173     lock_ObtainWrite(&scp->rw);
3174     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
3175                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3176     lock_ReleaseWrite(&scp->rw);
3177     if (code) {
3178         cm_ReleaseSCache(scp);
3179         osi_Log2(afsd_logp, "RDR_RequestFileExtentsAsync cm_SyncOp failure scp=0x%p code=0x%x",
3180                  scp, code);
3181         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3182         RDR_SetFileStatus( &scp->fid, status);
3183         return FALSE;
3184     }
3185
3186     /* Allocate the extents from the buffer package */
3187     for ( count = 0,
3188           ByteOffset = BeginOffset = RequestExtentsCB->ByteOffset,
3189           EndOffset.QuadPart = ByteOffset.QuadPart + RequestExtentsCB->Length;
3190           code == 0 && ByteOffset.QuadPart < EndOffset.QuadPart;
3191           ByteOffset.QuadPart += cm_data.blockSize)
3192     {
3193         BOOL bHaveBuffer = FALSE;
3194
3195         QueueLength = 0;
3196         thyper.QuadPart = ByteOffset.QuadPart;
3197
3198         code = buf_Get(scp, &thyper, &req, &bufp);
3199         if (code == 0) {
3200             lock_ObtainMutex(&bufp->mx);
3201             bBufRelease = TRUE;
3202
3203             if (bufp->qFlags & CM_BUF_QREDIR) {
3204                 bHaveBuffer = TRUE;
3205             } else if (bufp->flags & CM_BUF_DIRTY) {
3206                 bHaveBuffer = FALSE;
3207 #if 0
3208                 code = buf_CleanAsyncLocked(scp, bufp, &req, 0, NULL);
3209                 switch (code) {
3210                 case 0:
3211                     bHaveBuffer = TRUE;
3212                     break;
3213                 case CM_ERROR_RETRY:
3214                     /* Couldn't flush it, obtain it asynchronously so we don't block the thread. */
3215                     bHaveBuffer = FALSE;
3216                     code = 0;
3217                     break;
3218                 default:
3219                     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3220                     RDR_SetFileStatus(&FileId, status);
3221                     bHaveBuffer = FALSE;
3222                     code = 0;
3223                 }
3224 #endif
3225             } else {
3226                 osi_hyper_t minLength;  /* effective end of file */
3227
3228                 lock_ObtainRead(&scp->rw);
3229                 bHaveBuffer = cm_HaveBuffer(scp, bufp, TRUE);
3230
3231                 if (LargeIntegerGreaterThan(scp->length, scp->serverLength))
3232                     minLength = scp->serverLength;
3233                 else
3234                     minLength = scp->length;
3235
3236                 if (LargeIntegerGreaterThanOrEqualTo(bufp->offset, minLength)) {
3237                     memset(bufp->datap, 0, cm_data.buf_blockSize);
3238                     bufp->dataVersion = scp->dataVersion;
3239                     bHaveBuffer = TRUE;
3240                 }
3241                 lock_ReleaseRead(&scp->rw);
3242
3243                 if ((RequestExtentsCB->Flags & AFS_EXTENT_FLAG_CLEAN) &&
3244                      ByteOffset.QuadPart <= bufp->offset.QuadPart &&
3245                      EndOffset.QuadPart >= bufp->offset.QuadPart + cm_data.blockSize) {
3246                     memset(bufp->datap, 0, cm_data.blockSize);
3247                     bufp->dataVersion = scp->dataVersion;
3248                     buf_SetDirty(bufp, &req, 0, cm_data.blockSize, userp);
3249                     bHaveBuffer = TRUE;
3250                 }
3251             }
3252
3253             /*
3254              * if this buffer is already up to date, skip it.
3255              */
3256             if (bHaveBuffer) {
3257                 if (ByteOffset.QuadPart == BeginOffset.QuadPart) {
3258                     BeginOffset.QuadPart += cm_data.blockSize;
3259                 } else {
3260                     QueueLength = (afs_uint32)(ByteOffset.QuadPart - BeginOffset.QuadPart);
3261                     QueueOffset = BeginOffset;
3262                     BeginOffset = ByteOffset;
3263                 }
3264
3265                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3266 #ifdef VALIDATE_CHECK_SUM
3267 #ifdef ODS_DEBUG
3268                     char md5dbg[33];
3269                     char dbgstr[1024];
3270 #endif
3271 #endif
3272                     lock_ObtainWrite(&scp->rw);
3273                     lock_ObtainWrite(&buf_globalLock);
3274                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3275                         buf_InsertToRedirQueue(scp, bufp);
3276                         lock_ReleaseWrite(&buf_globalLock);
3277                         lock_ReleaseWrite(&scp->rw);
3278
3279 #ifdef VALIDATE_CHECK_SUM
3280                         buf_ComputeCheckSum(bufp);
3281 #endif
3282                         /* we already have the buffer, return it now */
3283                         pResultCB->FileExtents[count].Flags = 0;
3284                         pResultCB->FileExtents[count].FileOffset = ByteOffset;
3285                         pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3286                         pResultCB->FileExtents[count].Length = cm_data.blockSize;
3287                         count++;
3288
3289                         bBufRelease = FALSE;
3290
3291 #ifdef VALIDATE_CHECK_SUM
3292 #ifdef ODS_DEBUG
3293                         HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3294                         snprintf( dbgstr, 1024,
3295                                   "RDR_RequestFileExtentsAsync md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3296                                   md5dbg,
3297                                   scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3298                                   pResultCB->FileExtents[count].FileOffset.HighPart,
3299                                   pResultCB->FileExtents[count].FileOffset.LowPart,
3300                                   pResultCB->FileExtents[count].CacheOffset.HighPart,
3301                                   pResultCB->FileExtents[count].CacheOffset.LowPart);
3302                         OutputDebugStringA( dbgstr);
3303 #endif
3304 #endif
3305                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3306                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3307                     } else {
3308                         lock_ReleaseWrite(&buf_globalLock);
3309                         lock_ReleaseWrite(&scp->rw);
3310                     }
3311                 } else {
3312                     if (bBufRelease) {
3313                         /*
3314                          * The service is not handing off the extent to the redirector in this pass.
3315                          * However, we know the buffer is in recent use so move the buffer to the
3316                          * front of the queue
3317                          */
3318                         lock_ObtainWrite(&scp->rw);
3319                         lock_ObtainWrite(&buf_globalLock);
3320                         buf_MoveToHeadOfRedirQueue(scp, bufp);
3321                         lock_ReleaseWrite(&buf_globalLock);
3322                         lock_ReleaseWrite(&scp->rw);
3323
3324                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3325                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3326                     }
3327                 }
3328             }
3329             lock_ReleaseMutex(&bufp->mx);
3330             if (bBufRelease)
3331                 buf_Release(bufp);
3332
3333      &n