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