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