Windows: Implement dynamic cell detection for RDR
[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 + 64) * 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          dscp == cm_data.rootSCachep) {
1066
1067         StringCchCopyNW(wszName, cbName, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH);
1068         if (wcschr(wszName, '%') != NULL || wcschr(wszName, '#') != NULL) {
1069             /*
1070              * A volume reference:  <cell>{%,#}<volume> -> @vol:<cell>{%,#}<volume>
1071              */
1072             StringCbCatNW(wszName, cbName, FileName, FileNameLength);
1073         } else {
1074             if (FileName[0] == L'.') {
1075                 StringCbCatNW(wszName, cbName, &FileName[1], FileNameLength);
1076                 StringCbCatNW(wszName, cbName, L"%", sizeof(WCHAR));
1077             } else {
1078                 StringCbCatNW(wszName, cbName, FileName, FileNameLength);
1079                 StringCbCatNW(wszName, cbName, L"#", sizeof(WCHAR));
1080             }
1081             StringCbCatNW(wszName, cbName, L"root.cell", 9 * sizeof(WCHAR));
1082         }
1083         bVol = TRUE;
1084
1085         code = cm_EvaluateVolumeReference(wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1086     }
1087
1088     if (code == 0 && scp) {
1089         wchar_t shortName[13]=L"";
1090
1091         if (!cm_shortNames) {
1092             shortName[0] = L'\0';
1093         } else if (bVol) {
1094             cm_Gen8Dot3VolNameW(scp->fid.cell, scp->fid.volume, shortName, NULL);
1095         } else if (!cm_Is8Dot3(wszName)) {
1096             cm_dirFid_t dfid;
1097
1098             dfid.vnode = htonl(scp->fid.vnode);
1099             dfid.unique = htonl(scp->fid.unique);
1100
1101             cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1102         } else {
1103             shortName[0] = L'\0';
1104         }
1105
1106         code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1107                                         dscp, scp, userp, &req,
1108                                         FileName, shortName,
1109                                         (bWow64 ? RDR_POP_WOW64 : 0) |
1110                                         (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1111                                         0, NULL, &dwRemaining);
1112         if (bHoldFid)
1113             RDR_FlagScpInUse( scp, FALSE );
1114         cm_ReleaseSCache(scp);
1115
1116         if (code) {
1117             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1118             (*ResultCB)->ResultStatus = status;
1119             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1120                       code, status);
1121         } else {
1122             pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1123             (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1124             (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1125             osi_Log0(afsd_logp, "RDR_EvaluateNodeByName SUCCESS");
1126         }
1127     } else if (code) {
1128         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1129         (*ResultCB)->ResultStatus = status;
1130         osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1131                  code, status);
1132     } else {
1133         (*ResultCB)->ResultStatus = STATUS_NO_SUCH_FILE;
1134         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName No Such File");
1135     }
1136     cm_ReleaseSCache(dscp);
1137     free(wszName);
1138
1139     return;
1140 }
1141
1142 void
1143 RDR_EvaluateNodeByID( IN cm_user_t *userp,
1144                       IN AFSFileID ParentID,            /* not used */
1145                       IN AFSFileID SourceID,
1146                       IN BOOL      bWow64,
1147                       IN BOOL      bNoFollow,
1148                       IN BOOL      bHoldFid,
1149                       IN DWORD     ResultBufferLength,
1150                       IN OUT AFSCommResult **ResultCB)
1151 {
1152     AFSFileEvalResultCB *pEvalResultCB = NULL;
1153     AFSDirEnumEntry * pCurrentEntry = NULL;
1154     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
1155     afs_uint32  code = 0;
1156     cm_scache_t * scp = NULL;
1157     cm_scache_t * dscp = NULL;
1158     cm_req_t      req;
1159     cm_fid_t      Fid;
1160     cm_fid_t      parentFid;
1161     DWORD         status;
1162     DWORD         dwRemaining;
1163
1164     osi_Log4(afsd_logp, "RDR_EvaluateNodeByID source FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1165               SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1166     osi_Log4(afsd_logp, "... parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1167               ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1168
1169     *ResultCB = (AFSCommResult *)malloc(size);
1170     if (!(*ResultCB)) {
1171         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Out of Memory");
1172         return;
1173     }
1174
1175     memset(*ResultCB, 0, size);
1176     (*ResultCB)->ResultBufferLength = 0;
1177     dwRemaining = ResultBufferLength;
1178     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1179         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1180         pCurrentEntry = &pEvalResultCB->DirEnum;
1181         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1182     }
1183
1184     RDR_InitReq(&req, bWow64);
1185
1186     if (SourceID.Cell != 0) {
1187         cm_SetFid(&Fid, SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1188         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
1189         if (code) {
1190             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1191             (*ResultCB)->ResultStatus = status;
1192             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache SourceFID failure code=0x%x status=0x%x",
1193                       code, status);
1194             return;
1195         }
1196     } else {
1197         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1198         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Name Invalid - Cell = 0");
1199         return;
1200     }
1201
1202     if (ParentID.Cell != 0) {
1203         cm_SetFid(&parentFid, ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1204         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1205         if (code) {
1206             cm_ReleaseSCache(scp);
1207             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1208             if ( status == STATUS_INVALID_HANDLE)
1209                 status = STATUS_OBJECT_PATH_INVALID;
1210             (*ResultCB)->ResultStatus = status;
1211             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1212                       code, status);
1213             return;
1214         }
1215     } else if (SourceID.Vnode == 1) {
1216         dscp = scp;
1217         cm_HoldSCache(dscp);
1218     } else if (scp->parentVnode) {
1219         cm_SetFid(&parentFid, SourceID.Cell, SourceID.Volume, scp->parentVnode, scp->parentUnique);
1220         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1221         if (code) {
1222             cm_ReleaseSCache(scp);
1223             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1224             if ( status == STATUS_INVALID_HANDLE)
1225                 status = STATUS_OBJECT_PATH_INVALID;
1226             (*ResultCB)->ResultStatus = status;
1227             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1228                       code, status);
1229             return;
1230         }
1231     } else {
1232         (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
1233         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Path Invalid - Unknown Parent");
1234         return;
1235     }
1236
1237     /* Make sure the directory is current */
1238     lock_ObtainWrite(&dscp->rw);
1239     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1240                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1241     if (code) {
1242         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1243         (*ResultCB)->ResultStatus = status;
1244         lock_ReleaseWrite(&dscp->rw);
1245         cm_ReleaseSCache(dscp);
1246         cm_ReleaseSCache(scp);
1247         osi_Log3(afsd_logp, "RDR_EvaluateNodeByID cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1248                  dscp, code, status);
1249         return;
1250     }
1251
1252     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1253     lock_ReleaseWrite(&dscp->rw);
1254
1255     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1256         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1257         cm_ReleaseSCache(dscp);
1258         cm_ReleaseSCache(scp);
1259         osi_Log1(afsd_logp, "RDR_EvaluateNodeByID Not a Directory dscp=0x%p", dscp);
1260         return;
1261     }
1262
1263     code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1264                                     dscp, scp, userp, &req, NULL, NULL,
1265                                     (bWow64 ? RDR_POP_WOW64 : 0) |
1266                                     (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1267                                     0, NULL, &dwRemaining);
1268
1269     if (bHoldFid)
1270         RDR_FlagScpInUse( scp, FALSE );
1271     cm_ReleaseSCache(scp);
1272     cm_ReleaseSCache(dscp);
1273
1274     if (code) {
1275         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1276         (*ResultCB)->ResultStatus = status;
1277         osi_Log2(afsd_logp, "RDR_EvaluateNodeByID FAILURE code=0x%x status=0x%x",
1278                  code, status);
1279     } else {
1280         pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1281
1282         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1283         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1284         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID SUCCESS");
1285     }
1286     return;
1287 }
1288
1289 void
1290 RDR_CreateFileEntry( IN cm_user_t *userp,
1291                      IN WCHAR *FileNameCounted,
1292                      IN DWORD FileNameLength,
1293                      IN AFSFileCreateCB *CreateCB,
1294                      IN BOOL bWow64,
1295                      IN BOOL bHoldFid,
1296                      IN DWORD ResultBufferLength,
1297                      IN OUT AFSCommResult **ResultCB)
1298 {
1299     AFSFileCreateResultCB *pResultCB = NULL;
1300     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1301     cm_fid_t            parentFid;
1302     afs_uint32          code;
1303     cm_scache_t *       dscp = NULL;
1304     afs_uint32          flags = 0;
1305     cm_attr_t           setAttr;
1306     cm_scache_t *       scp = NULL;
1307     cm_req_t            req;
1308     DWORD               status;
1309     wchar_t             FileName[260];
1310
1311     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1312
1313     osi_Log4(afsd_logp, "RDR_CreateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1314               CreateCB->ParentId.Cell, CreateCB->ParentId.Volume,
1315               CreateCB->ParentId.Vnode, CreateCB->ParentId.Unique);
1316     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, FileName));
1317
1318     RDR_InitReq(&req, bWow64);
1319     memset(&setAttr, 0, sizeof(cm_attr_t));
1320
1321     *ResultCB = (AFSCommResult *)malloc(size);
1322     if (!(*ResultCB)) {
1323         osi_Log0(afsd_logp, "RDR_CreateFileEntry out of memory");
1324         return;
1325     }
1326
1327     memset( *ResultCB,
1328             '\0',
1329             size);
1330
1331     parentFid.cell   = CreateCB->ParentId.Cell;
1332     parentFid.volume = CreateCB->ParentId.Volume;
1333     parentFid.vnode  = CreateCB->ParentId.Vnode;
1334     parentFid.unique = CreateCB->ParentId.Unique;
1335     parentFid.hash   = CreateCB->ParentId.Hash;
1336
1337     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1338     if (code) {
1339         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1340         (*ResultCB)->ResultStatus = status;
1341         if ( status == STATUS_INVALID_HANDLE)
1342             status = STATUS_OBJECT_PATH_INVALID;
1343         osi_Log2(afsd_logp, "RDR_CreateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1344                   code, status);
1345         return;
1346     }
1347
1348     lock_ObtainWrite(&dscp->rw);
1349     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1350                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1351     if (code) {
1352         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1353         (*ResultCB)->ResultStatus = status;
1354         lock_ReleaseWrite(&dscp->rw);
1355         cm_ReleaseSCache(dscp);
1356         osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (1) dscp=0x%p code=0x%x status=0x%x",
1357                  dscp, code, status);
1358         return;
1359     }
1360
1361     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1362     lock_ReleaseWrite(&dscp->rw);
1363
1364     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1365         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1366         cm_ReleaseSCache(dscp);
1367         osi_Log1(afsd_logp, "RDR_CreateFileEntry Not a Directory dscp=0x%p",
1368                  dscp);
1369         return;
1370     }
1371
1372     /* Use current time */
1373     setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
1374     setAttr.clientModTime = time(NULL);
1375
1376     if (CreateCB->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1377         if (smb_unixModeDefaultDir) {
1378             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1379             setAttr.unixModeBits = smb_unixModeDefaultDir;
1380             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1381                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1382         }
1383
1384         code = cm_MakeDir(dscp, FileName, flags, &setAttr, userp, &req, &scp);
1385     } else {
1386         if (smb_unixModeDefaultFile) {
1387             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1388             setAttr.unixModeBits = smb_unixModeDefaultFile;
1389             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1390                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1391         }
1392
1393         setAttr.mask |= CM_ATTRMASK_LENGTH;
1394         setAttr.length.LowPart = CreateCB->AllocationSize.LowPart;
1395         setAttr.length.HighPart = CreateCB->AllocationSize.HighPart;
1396         code = cm_Create(dscp, FileName, flags, &setAttr, &scp, userp, &req);
1397     }
1398     if (code == 0) {
1399         wchar_t shortName[13]=L"";
1400         cm_dirFid_t dfid;
1401         DWORD dwRemaining;
1402
1403         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
1404
1405         (*ResultCB)->ResultBufferLength = sizeof( AFSFileCreateResultCB);
1406
1407         pResultCB = (AFSFileCreateResultCB *)(*ResultCB)->ResultData;
1408
1409         dwRemaining = ResultBufferLength - sizeof( AFSFileCreateResultCB) + sizeof( AFSDirEnumEntry);
1410
1411         lock_ObtainWrite(&dscp->rw);
1412         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1413                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1414         if (code) {
1415             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1416             (*ResultCB)->ResultStatus = status;
1417             lock_ReleaseWrite(&dscp->rw);
1418             cm_ReleaseSCache(dscp);
1419             cm_ReleaseSCache(scp);
1420             osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (2) dscp=0x%p code=0x%x status=0x%x",
1421                       dscp, code, status);
1422             return;
1423         }
1424
1425         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1426
1427         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1428         lock_ReleaseWrite(&dscp->rw);
1429
1430         if (cm_shortNames) {
1431             dfid.vnode = htonl(scp->fid.vnode);
1432             dfid.unique = htonl(scp->fid.unique);
1433
1434             if (!cm_Is8Dot3(FileName))
1435                 cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1436             else
1437                 shortName[0] = '\0';
1438         }
1439
1440         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1441                                         dscp, scp, userp, &req, FileName, shortName,
1442                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1443                                         0, NULL, &dwRemaining);
1444
1445         if (bHoldFid)
1446             RDR_FlagScpInUse( scp, FALSE );
1447         cm_ReleaseSCache(scp);
1448         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1449         osi_Log0(afsd_logp, "RDR_CreateFileEntry SUCCESS");
1450     } else {
1451         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1452         (*ResultCB)->ResultStatus = status;
1453         (*ResultCB)->ResultBufferLength = 0;
1454         osi_Log2(afsd_logp, "RDR_CreateFileEntry FAILURE code=0x%x status=0x%x",
1455                   code, status);
1456     }
1457
1458     cm_ReleaseSCache(dscp);
1459
1460     return;
1461 }
1462
1463 void
1464 RDR_UpdateFileEntry( IN cm_user_t *userp,
1465                      IN AFSFileID FileId,
1466                      IN AFSFileUpdateCB *UpdateCB,
1467                      IN BOOL bWow64,
1468                      IN DWORD ResultBufferLength,
1469                      IN OUT AFSCommResult **ResultCB)
1470 {
1471     AFSFileUpdateResultCB *pResultCB = NULL;
1472     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1473     cm_fid_t            Fid;
1474     cm_fid_t            parentFid;
1475     afs_uint32          code;
1476     afs_uint32          flags = 0;
1477     cm_attr_t           setAttr;
1478     cm_scache_t *       scp = NULL;
1479     cm_scache_t *       dscp = NULL;
1480     cm_req_t            req;
1481     time_t              clientModTime;
1482     FILETIME            ft;
1483     DWORD               status;
1484     BOOL                bScpLocked = FALSE;
1485
1486     RDR_InitReq(&req, bWow64);
1487     memset(&setAttr, 0, sizeof(cm_attr_t));
1488
1489     osi_Log4(afsd_logp, "RDR_UpdateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1490               UpdateCB->ParentId.Cell, UpdateCB->ParentId.Volume,
1491               UpdateCB->ParentId.Vnode, UpdateCB->ParentId.Unique);
1492     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1493               FileId.Cell, FileId.Volume,
1494               FileId.Vnode, FileId.Unique);
1495
1496     *ResultCB = (AFSCommResult *)malloc( size);
1497     if (!(*ResultCB)) {
1498         osi_Log0(afsd_logp, "RDR_UpdateFileEntry Out of Memory");
1499         return;
1500     }
1501
1502     memset( *ResultCB,
1503             '\0',
1504             size);
1505
1506     parentFid.cell   = UpdateCB->ParentId.Cell;
1507     parentFid.volume = UpdateCB->ParentId.Volume;
1508     parentFid.vnode  = UpdateCB->ParentId.Vnode;
1509     parentFid.unique = UpdateCB->ParentId.Unique;
1510     parentFid.hash   = UpdateCB->ParentId.Hash;
1511
1512     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1513     if (code) {
1514         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1515         (*ResultCB)->ResultStatus = status;
1516         if ( status == STATUS_INVALID_HANDLE)
1517             status = STATUS_OBJECT_PATH_INVALID;
1518         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1519                   code, status);
1520         return;
1521     }
1522
1523     lock_ObtainWrite(&dscp->rw);
1524     bScpLocked = TRUE;
1525     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1526                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1527     if (code) {
1528         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1529         (*ResultCB)->ResultStatus = status;
1530         lock_ReleaseWrite(&dscp->rw);
1531         cm_ReleaseSCache(dscp);
1532         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1533                  dscp, code, status);
1534         return;
1535     }
1536
1537     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1538     lock_ReleaseWrite(&dscp->rw);
1539     bScpLocked = FALSE;
1540
1541     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1542         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1543         cm_ReleaseSCache(dscp);
1544         osi_Log1(afsd_logp, "RDR_UpdateFileEntry Not a Directory dscp=0x%p",
1545                  dscp);
1546         return;
1547     }
1548
1549     Fid.cell   = FileId.Cell;
1550     Fid.volume = FileId.Volume;
1551     Fid.vnode  = FileId.Vnode;
1552     Fid.unique = FileId.Unique;
1553     Fid.hash   = FileId.Hash;
1554
1555     code = cm_GetSCache(&Fid, &dscp->fid, &scp, userp, &req);
1556     if (code) {
1557         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1558         (*ResultCB)->ResultStatus = status;
1559         cm_ReleaseSCache(dscp);
1560         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache object FID failure code=0x%x status=0x%x",
1561                   code, status);
1562         return;
1563     }
1564
1565     lock_ObtainWrite(&scp->rw);
1566     bScpLocked = TRUE;
1567     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1568                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1569     if (code) {
1570         lock_ReleaseWrite(&scp->rw);
1571         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1572         (*ResultCB)->ResultStatus = status;
1573         (*ResultCB)->ResultBufferLength = 0;
1574         cm_ReleaseSCache(dscp);
1575         cm_ReleaseSCache(scp);
1576         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
1577                  scp, code, status);
1578         return;
1579     }
1580     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1581
1582     if (UpdateCB->ChangeTime.QuadPart) {
1583
1584         if (scp->fileType == CM_SCACHETYPE_FILE) {
1585             /* Do not set length and other attributes at the same time */
1586             if (scp->length.QuadPart != UpdateCB->AllocationSize.QuadPart) {
1587                 osi_Log2(afsd_logp, "RDR_UpdateFileEntry Length Change 0x%x -> 0x%x",
1588                           (afs_uint32)scp->length.QuadPart, (afs_uint32)UpdateCB->AllocationSize.QuadPart);
1589                 setAttr.mask |= CM_ATTRMASK_LENGTH;
1590                 setAttr.length.LowPart = UpdateCB->AllocationSize.LowPart;
1591                 setAttr.length.HighPart = UpdateCB->AllocationSize.HighPart;
1592                 lock_ReleaseWrite(&scp->rw);
1593                 bScpLocked = FALSE;
1594                 code = cm_SetAttr(scp, &setAttr, userp, &req);
1595                 if (code)
1596                     goto on_error;
1597                 setAttr.mask = 0;
1598             }
1599         }
1600
1601         if (!bScpLocked) {
1602             lock_ObtainWrite(&scp->rw);
1603             bScpLocked = TRUE;
1604         }
1605         if ((scp->unixModeBits & 0200) && (UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1606             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1607             setAttr.unixModeBits = scp->unixModeBits & ~0222;
1608         } else if (!(scp->unixModeBits & 0200) && !(UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1609             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1610             setAttr.unixModeBits = scp->unixModeBits | 0222;
1611         }
1612     }
1613
1614     if (UpdateCB->LastWriteTime.QuadPart) {
1615         ft.dwLowDateTime = UpdateCB->LastWriteTime.LowPart;
1616         ft.dwHighDateTime = UpdateCB->LastWriteTime.HighPart;
1617
1618         cm_UnixTimeFromLargeSearchTime(& clientModTime, &ft);
1619
1620         if (!bScpLocked) {
1621             lock_ObtainWrite(&scp->rw);
1622             bScpLocked = TRUE;
1623         }
1624         if (scp->clientModTime != clientModTime) {
1625             setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1626             setAttr.clientModTime = clientModTime;
1627         }
1628
1629         /* call setattr */
1630         if (setAttr.mask) {
1631             lock_ReleaseWrite(&scp->rw);
1632             bScpLocked = FALSE;
1633             code = cm_SetAttr(scp, &setAttr, userp, &req);
1634         } else
1635             code = 0;
1636     }
1637
1638   on_error:
1639     if (bScpLocked) {
1640         lock_ReleaseWrite(&scp->rw);
1641     }
1642
1643     if (code == 0) {
1644         DWORD dwRemaining = ResultBufferLength - sizeof( AFSFileUpdateResultCB) + sizeof( AFSDirEnumEntry);
1645
1646         pResultCB = (AFSFileUpdateResultCB *)(*ResultCB)->ResultData;
1647
1648         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1649
1650         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1651                                         dscp, scp, userp, &req, NULL, NULL,
1652                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1653                                         0, NULL, &dwRemaining);
1654         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1655         osi_Log0(afsd_logp, "RDR_UpdateFileEntry SUCCESS");
1656     } else {
1657         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1658         (*ResultCB)->ResultStatus = status;
1659         (*ResultCB)->ResultBufferLength = 0;
1660         osi_Log2(afsd_logp, "RDR_UpdateFileEntry FAILURE code=0x%x status=0x%x",
1661                   code, status);
1662     }
1663     cm_ReleaseSCache(scp);
1664     cm_ReleaseSCache(dscp);
1665
1666     return;
1667 }
1668
1669 void
1670 RDR_CleanupFileEntry( IN cm_user_t *userp,
1671                       IN AFSFileID FileId,
1672                       IN WCHAR *FileNameCounted,
1673                       IN DWORD FileNameLength,
1674                       IN AFSFileCleanupCB *CleanupCB,
1675                       IN BOOL bWow64,
1676                       IN BOOL bLastHandle,
1677                       IN BOOL bDeleteFile,
1678                       IN BOOL bUnlockFile,
1679                       IN DWORD ResultBufferLength,
1680                       IN OUT AFSCommResult **ResultCB)
1681 {
1682     AFSFileCleanupResultCB *pResultCB = NULL;
1683     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1684     cm_fid_t            Fid;
1685     cm_fid_t            parentFid;
1686     afs_uint32          code = 0;
1687     afs_uint32          flags = 0;
1688     cm_attr_t           setAttr;
1689     cm_scache_t *       scp = NULL;
1690     cm_scache_t *       dscp = NULL;
1691     cm_req_t            req;
1692     time_t              clientModTime;
1693     FILETIME            ft;
1694     DWORD               status;
1695     BOOL                bScpLocked = FALSE;
1696     BOOL                bDscpLocked = FALSE;
1697     BOOL                bFlushFile = FALSE;
1698     cm_key_t            key;
1699
1700     RDR_InitReq(&req, bWow64);
1701     memset(&setAttr, 0, sizeof(cm_attr_t));
1702
1703     osi_Log4(afsd_logp, "RDR_CleanupFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1704               CleanupCB->ParentId.Cell, CleanupCB->ParentId.Volume,
1705               CleanupCB->ParentId.Vnode, CleanupCB->ParentId.Unique);
1706     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1707               FileId.Cell, FileId.Volume,
1708               FileId.Vnode, FileId.Unique);
1709
1710     *ResultCB = (AFSCommResult *)malloc( size);
1711     if (!(*ResultCB)) {
1712         osi_Log0(afsd_logp, "RDR_CleanupFileEntry Out of Memory");
1713         return;
1714     }
1715
1716     memset( *ResultCB,
1717             '\0',
1718             size);
1719
1720     parentFid.cell   = CleanupCB->ParentId.Cell;
1721     parentFid.volume = CleanupCB->ParentId.Volume;
1722     parentFid.vnode  = CleanupCB->ParentId.Vnode;
1723     parentFid.unique = CleanupCB->ParentId.Unique;
1724     parentFid.hash   = CleanupCB->ParentId.Hash;
1725
1726     if (parentFid.cell) {
1727         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1728         if (code) {
1729             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1730             if ( status == STATUS_INVALID_HANDLE)
1731                 status = STATUS_OBJECT_PATH_INVALID;
1732             (*ResultCB)->ResultStatus = status;
1733             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1734                      code, status);
1735             return;
1736         }
1737
1738         lock_ObtainWrite(&dscp->rw);
1739         bDscpLocked = TRUE;
1740         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1741                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1742         if (code) {
1743             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure dscp=0x%p code=0x%x",
1744                     dscp, code);
1745             if (code)
1746                 goto on_error;
1747         }
1748
1749         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1750         lock_ReleaseWrite(&dscp->rw);
1751         bDscpLocked = FALSE;
1752
1753         if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1754             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1755             cm_ReleaseSCache(dscp);
1756             osi_Log1(afsd_logp, "RDR_CleanupFileEntry Not a Directory dscp=0x%p",
1757                      dscp);
1758             if (code)
1759                 goto on_error;
1760         }
1761     }
1762
1763     Fid.cell   = FileId.Cell;
1764     Fid.volume = FileId.Volume;
1765     Fid.vnode  = FileId.Vnode;
1766     Fid.unique = FileId.Unique;
1767     Fid.hash   = FileId.Hash;
1768
1769     code = cm_GetSCache(&Fid, dscp ? &dscp->fid : NULL, &scp, userp, &req);
1770     if (code) {
1771         osi_Log1(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache object FID failure code=0x%x",
1772                  code);
1773         goto on_error;
1774     }
1775
1776     lock_ObtainWrite(&scp->rw);
1777     bScpLocked = TRUE;
1778     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1779                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1780     if (code) {
1781         osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure scp=0x%p code=0x%x",
1782                  scp, code);
1783         goto on_error;
1784     }
1785     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1786
1787     if ((bLastHandle || bFlushFile) &&
1788         scp->redirBufCount > 0)
1789     {
1790         LARGE_INTEGER heldExtents;
1791         AFSFileExtentCB extentList[1024];
1792         DWORD extentCount = 0;
1793         cm_buf_t *srbp;
1794         time_t now;
1795
1796         time(&now);
1797         heldExtents.QuadPart = 0;
1798
1799         for ( srbp = redirq_to_cm_buf_t(scp->redirQueueT);
1800               srbp;
1801               srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1802         {
1803             extentList[extentCount].Flags = 0;
1804             extentList[extentCount].Length = cm_data.blockSize;
1805             extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1806             extentList[extentCount].CacheOffset.QuadPart = srbp->datap - RDR_extentBaseAddress;
1807             lock_ObtainWrite(&buf_globalLock);
1808             srbp->redirReleaseRequested = now;
1809             lock_ReleaseWrite(&buf_globalLock);
1810             extentCount++;
1811
1812             if (extentCount == 1024) {
1813                 lock_ReleaseWrite(&scp->rw);
1814                 code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1815                 if (code) {
1816                     if (code == CM_ERROR_RETRY) {
1817                         /*
1818                          * The redirector either is not holding the extents or cannot let them
1819                          * go because they are otherwise in use.  At the moment, do nothing.
1820                          */
1821                     } else
1822                         break;
1823                 }
1824                 extentCount = 0;
1825                 bFlushFile = TRUE;
1826                 lock_ObtainWrite(&scp->rw);
1827             }
1828         }
1829
1830         if (code == 0 && extentCount > 0) {
1831             if (bScpLocked) {
1832                 lock_ReleaseWrite(&scp->rw);
1833                 bScpLocked = FALSE;
1834             }
1835             code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1836             bFlushFile = TRUE;
1837         }
1838     }
1839
1840     /* No longer in use by redirector */
1841     if (!bScpLocked) {
1842         lock_ObtainWrite(&scp->rw);
1843         bScpLocked = TRUE;
1844     }
1845
1846     if (bLastHandle) {
1847         lock_AssertWrite(&scp->rw);
1848         scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
1849     }
1850
1851     /* If not a readonly object, flush dirty data and update metadata */
1852     if (!(scp->flags & CM_SCACHEFLAG_RO)) {
1853         if ((bLastHandle || bFlushFile) &&
1854              buf_DirtyBuffersExist(&scp->fid)) {
1855             if (!bScpLocked) {
1856                 lock_ObtainWrite(&scp->rw);
1857                 bScpLocked = TRUE;
1858             }
1859             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
1860                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1861             if (code == 0) {
1862                 if (bScpLocked) {
1863                     lock_ReleaseWrite(&scp->rw);
1864                     bScpLocked = FALSE;
1865                 }
1866
1867                 code = cm_FSync(scp, userp, &req, bScpLocked);
1868             }
1869             if (bLastHandle && code)
1870                 goto unlock;
1871         }
1872
1873         if (CleanupCB->ChangeTime.QuadPart) {
1874
1875             if (scp->fileType == CM_SCACHETYPE_FILE) {
1876                 /* Do not set length and other attributes at the same time */
1877                 if (scp->length.QuadPart != CleanupCB->AllocationSize.QuadPart) {
1878                     osi_Log2(afsd_logp, "RDR_CleanupFileEntry Length Change 0x%x -> 0x%x",
1879                              (afs_uint32)scp->length.QuadPart, (afs_uint32)CleanupCB->AllocationSize.QuadPart);
1880                     setAttr.mask |= CM_ATTRMASK_LENGTH;
1881                     setAttr.length.LowPart = CleanupCB->AllocationSize.LowPart;
1882                     setAttr.length.HighPart = CleanupCB->AllocationSize.HighPart;
1883
1884                     if (bScpLocked) {
1885                         lock_ReleaseWrite(&scp->rw);
1886                         bScpLocked = FALSE;
1887                     }
1888                     code = cm_SetAttr(scp, &setAttr, userp, &req);
1889                     if (code)
1890                         goto unlock;
1891                     setAttr.mask = 0;
1892                 }
1893             }
1894
1895             if (!bScpLocked) {
1896                 lock_ObtainWrite(&scp->rw);
1897                 bScpLocked = TRUE;
1898             }
1899
1900             if ((scp->unixModeBits & 0200) && (CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1901                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1902                 setAttr.unixModeBits = scp->unixModeBits & ~0222;
1903             } else if (!(scp->unixModeBits & 0200) && !(CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1904                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1905                 setAttr.unixModeBits = scp->unixModeBits | 0222;
1906             }
1907         }
1908
1909         if (CleanupCB->LastWriteTime.QuadPart) {
1910             ft.dwLowDateTime = CleanupCB->LastWriteTime.LowPart;
1911             ft.dwHighDateTime = CleanupCB->LastWriteTime.HighPart;
1912
1913             cm_UnixTimeFromLargeSearchTime(&clientModTime, &ft);
1914             if (scp->clientModTime != clientModTime) {
1915                 setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1916                 setAttr.clientModTime = clientModTime;
1917             }
1918         }
1919
1920         /* call setattr */
1921         if (setAttr.mask) {
1922             if (bScpLocked) {
1923                 lock_ReleaseWrite(&scp->rw);
1924                 bScpLocked = FALSE;
1925             }
1926             code = cm_SetAttr(scp, &setAttr, userp, &req);
1927         } else
1928             code = 0;
1929     }
1930
1931   unlock:
1932     /* Now drop the lock enforcing the share access */
1933     if ( CleanupCB->FileAccess != AFS_FILE_ACCESS_NOLOCK) {
1934         unsigned int sLockType;
1935         LARGE_INTEGER LOffset, LLength;
1936
1937         if (CleanupCB->FileAccess == AFS_FILE_ACCESS_SHARED)
1938             sLockType = LOCKING_ANDX_SHARED_LOCK;
1939         else
1940             sLockType = 0;
1941
1942         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, CleanupCB->Identifier);
1943
1944         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
1945         LOffset.LowPart = SMB_FID_QLOCK_LOW;
1946         LLength.HighPart = 0;
1947         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
1948
1949         if (!bScpLocked) {
1950             lock_ObtainWrite(&scp->rw);
1951             bScpLocked = TRUE;
1952         }
1953
1954         code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
1955         if (code == 0)
1956         {
1957             code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
1958
1959             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
1960
1961             if (code == CM_ERROR_RANGE_NOT_LOCKED)
1962             {
1963                 osi_Log3(afsd_logp, "RDR_CleanupFileEntry Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
1964                          CleanupCB->FileAccess, CleanupCB->ProcessId, CleanupCB->Identifier);
1965
1966             }
1967         }
1968     }
1969
1970     if (bUnlockFile || bDeleteFile) {
1971         if (!bScpLocked) {
1972             lock_ObtainWrite(&scp->rw);
1973             bScpLocked = TRUE;
1974         }
1975         code = cm_SyncOp(scp, NULL, userp, &req, 0,
1976                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1977         if (code) {
1978             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp (2) failure scp=0x%p code=0x%x",
1979                      scp, code);
1980             goto on_error;
1981         }
1982
1983         key = cm_GenerateKey(CM_SESSION_IFS, CleanupCB->ProcessId, 0);
1984
1985         /* the scp is now locked and current */
1986         code = cm_UnlockByKey(scp, key,
1987                               bDeleteFile ? CM_UNLOCK_FLAG_BY_FID : 0,
1988                               userp, &req);
1989
1990         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1991
1992         if (code)
1993             goto on_error;
1994     }
1995
1996   on_error:
1997     if (bDscpLocked)
1998         lock_ReleaseWrite(&dscp->rw);
1999     if (bScpLocked)
2000         lock_ReleaseWrite(&scp->rw);
2001
2002     if (code == 0 && dscp && bDeleteFile) {
2003         WCHAR FileName[260];
2004
2005         StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2006
2007         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2008             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2009         else
2010             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2011     }
2012
2013     if (code == 0) {
2014         if ( ResultBufferLength >=  sizeof( AFSFileCleanupResultCB))
2015         {
2016             (*ResultCB)->ResultBufferLength = sizeof( AFSFileCleanupResultCB);
2017             pResultCB = (AFSFileCleanupResultCB *)&(*ResultCB)->ResultData;
2018             pResultCB->ParentDataVersion.QuadPart = dscp ? dscp->dataVersion : 0;
2019         } else {
2020             (*ResultCB)->ResultBufferLength = 0;
2021         }
2022
2023         (*ResultCB)->ResultStatus = 0;
2024         osi_Log0(afsd_logp, "RDR_CleanupFileEntry SUCCESS");
2025     } else {
2026         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2027         (*ResultCB)->ResultStatus = status;
2028         osi_Log2(afsd_logp, "RDR_CleanupFileEntry FAILURE code=0x%x status=0x%x",
2029                   code, status);
2030     }
2031
2032     if (scp)
2033         cm_ReleaseSCache(scp);
2034     if (dscp)
2035         cm_ReleaseSCache(dscp);
2036
2037     return;
2038 }
2039
2040 void
2041 RDR_DeleteFileEntry( IN cm_user_t *userp,
2042                      IN AFSFileID ParentId,
2043                      IN ULONGLONG ProcessId,
2044                      IN WCHAR *FileNameCounted,
2045                      IN DWORD FileNameLength,
2046                      IN BOOL bWow64,
2047                      IN BOOL bCheckOnly,
2048                      IN DWORD ResultBufferLength,
2049                      IN OUT AFSCommResult **ResultCB)
2050 {
2051
2052     AFSFileDeleteResultCB *pResultCB = NULL;
2053     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2054     cm_fid_t            parentFid;
2055     afs_uint32          code;
2056     cm_scache_t *       dscp = NULL;
2057     cm_scache_t *       scp = NULL;
2058     afs_uint32          flags = 0;
2059     cm_attr_t           setAttr;
2060     cm_req_t            req;
2061     DWORD               status;
2062     wchar_t             FileName[260];
2063     cm_key_t            key;
2064
2065     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2066
2067     osi_Log4(afsd_logp, "RDR_DeleteFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2068               ParentId.Cell,  ParentId.Volume,
2069               ParentId.Vnode, ParentId.Unique);
2070     osi_Log2(afsd_logp, "... name=%S checkOnly=%x",
2071              osi_LogSaveStringW(afsd_logp, FileName),
2072              bCheckOnly);
2073
2074     RDR_InitReq(&req, bWow64);
2075     memset(&setAttr, 0, sizeof(cm_attr_t));
2076
2077     *ResultCB = (AFSCommResult *)malloc( size);
2078     if (!(*ResultCB)) {
2079         osi_Log0(afsd_logp, "RDR_DeleteFileEntry out of memory");
2080         return;
2081     }
2082
2083     memset( *ResultCB,
2084             '\0',
2085             size);
2086
2087     parentFid.cell   = ParentId.Cell;
2088     parentFid.volume = ParentId.Volume;
2089     parentFid.vnode  = ParentId.Vnode;
2090     parentFid.unique = ParentId.Unique;
2091     parentFid.hash   = ParentId.Hash;
2092
2093     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
2094     if (code) {
2095         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2096         if ( status == STATUS_INVALID_HANDLE)
2097             status = STATUS_OBJECT_PATH_INVALID;
2098         (*ResultCB)->ResultStatus = status;
2099         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
2100                   code, status);
2101         return;
2102     }
2103
2104     lock_ObtainWrite(&dscp->rw);
2105
2106     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
2107                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2108     if (code) {
2109         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2110         (*ResultCB)->ResultStatus = status;
2111         (*ResultCB)->ResultBufferLength = 0;
2112         lock_ReleaseWrite(&dscp->rw);
2113         cm_ReleaseSCache(dscp);
2114         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
2115                  dscp, code, status);
2116         return;
2117     }
2118
2119     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2120     lock_ReleaseWrite(&dscp->rw);
2121
2122     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2123         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2124         cm_ReleaseSCache(dscp);
2125         osi_Log1(afsd_logp, "RDR_DeleteFileEntry Not a Directory dscp=0x%p",
2126                  dscp);
2127         return;
2128     }
2129
2130     code = cm_Lookup(dscp, FileName, 0, userp, &req, &scp);
2131     if (code) {
2132         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2133         (*ResultCB)->ResultStatus = status;
2134         (*ResultCB)->ResultBufferLength = 0;
2135         cm_ReleaseSCache(dscp);
2136         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_Lookup failure code=0x%x status=0x%x",
2137                  code, status);
2138         return;
2139     }
2140
2141     lock_ObtainWrite(&scp->rw);
2142     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_DELETE,
2143                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2144     if (code) {
2145         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2146         (*ResultCB)->ResultStatus = status;
2147         (*ResultCB)->ResultBufferLength = 0;
2148         lock_ReleaseWrite(&scp->rw);
2149         cm_ReleaseSCache(scp);
2150         cm_ReleaseSCache(dscp);
2151         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2152                  scp, code, status);
2153         return;
2154     }
2155
2156     if (!bCheckOnly) {
2157         /* Drop all locks since the file is being deleted */
2158         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2159                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2160         if (code) {
2161             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2162             (*ResultCB)->ResultStatus = status;
2163             (*ResultCB)->ResultBufferLength = 0;
2164             lock_ReleaseWrite(&scp->rw);
2165             cm_ReleaseSCache(scp);
2166             cm_ReleaseSCache(dscp);
2167             osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp Lock failure scp=0x%p code=0x%x status=0x%x",
2168                      scp, code, status);
2169         }
2170
2171         /* the scp is now locked and current */
2172         key = cm_GenerateKey(CM_SESSION_IFS, ProcessId, 0);
2173
2174         code = cm_UnlockByKey(scp, key,
2175                               CM_UNLOCK_FLAG_BY_FID,
2176                               userp, &req);
2177
2178         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2179         lock_ReleaseWrite(&scp->rw);
2180
2181         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2182             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2183         else
2184             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2185     } else {
2186         lock_ReleaseWrite(&scp->rw);
2187     }
2188
2189     if (code == 0) {
2190         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
2191
2192         (*ResultCB)->ResultBufferLength = sizeof( AFSFileDeleteResultCB);
2193
2194         pResultCB = (AFSFileDeleteResultCB *)(*ResultCB)->ResultData;
2195
2196         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
2197         osi_Log0(afsd_logp, "RDR_DeleteFileEntry SUCCESS");
2198     } else {
2199         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2200         (*ResultCB)->ResultStatus = status;
2201         (*ResultCB)->ResultBufferLength = 0;
2202         osi_Log2(afsd_logp, "RDR_DeleteFileEntry FAILURE code=0x%x status=0x%x",
2203                   code, status);
2204     }
2205
2206     cm_ReleaseSCache(dscp);
2207     cm_ReleaseSCache(scp);
2208
2209     return;
2210 }
2211
2212 void
2213 RDR_RenameFileEntry( IN cm_user_t *userp,
2214                      IN WCHAR    *SourceFileNameCounted,
2215                      IN DWORD     SourceFileNameLength,
2216                      IN AFSFileID SourceFileId,
2217                      IN AFSFileRenameCB *pRenameCB,
2218                      IN BOOL bWow64,
2219                      IN DWORD ResultBufferLength,
2220                      IN OUT AFSCommResult **ResultCB)
2221 {
2222
2223     AFSFileRenameResultCB *pResultCB = NULL;
2224     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2225     AFSFileID              SourceParentId   = pRenameCB->SourceParentId;
2226     AFSFileID              TargetParentId   = pRenameCB->TargetParentId;
2227     WCHAR *                TargetFileNameCounted = pRenameCB->TargetName;
2228     DWORD                  TargetFileNameLength = pRenameCB->TargetNameLength;
2229     cm_fid_t               SourceParentFid;
2230     cm_fid_t               TargetParentFid;
2231     cm_fid_t               SourceFid;
2232     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2233     cm_fid_t               TargetFid;
2234     cm_scache_t *          oldDscp;
2235     cm_scache_t *          newDscp;
2236     cm_dirOp_t dirop;
2237     wchar_t                shortName[13];
2238     wchar_t                SourceFileName[260];
2239     wchar_t                TargetFileName[260];
2240     cm_dirFid_t            dfid;
2241     cm_req_t               req;
2242     afs_uint32             code;
2243     DWORD                  status;
2244
2245     RDR_InitReq(&req, bWow64);
2246
2247     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2248     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2249
2250     osi_Log4(afsd_logp, "RDR_RenameFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2251               SourceParentId.Cell,  SourceParentId.Volume,
2252               SourceParentId.Vnode, SourceParentId.Unique);
2253     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2254     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2255               TargetParentId.Cell,  TargetParentId.Volume,
2256               TargetParentId.Vnode, TargetParentId.Unique);
2257     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2258
2259     *ResultCB = (AFSCommResult *)malloc( size);
2260     if (!(*ResultCB))
2261         return;
2262
2263     memset( *ResultCB,
2264             '\0',
2265             size);
2266
2267     pResultCB = (AFSFileRenameResultCB *)(*ResultCB)->ResultData;
2268
2269     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2270     {
2271         osi_Log2(afsd_logp, "RDR_RenameFileEntry Invalid Name Length: src %u target %u",
2272                  SourceFileNameLength, TargetFileNameLength);
2273         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2274         return;
2275     }
2276
2277     SourceParentFid.cell   = SourceParentId.Cell;
2278     SourceParentFid.volume = SourceParentId.Volume;
2279     SourceParentFid.vnode  = SourceParentId.Vnode;
2280     SourceParentFid.unique = SourceParentId.Unique;
2281     SourceParentFid.hash   = SourceParentId.Hash;
2282
2283     TargetParentFid.cell   = TargetParentId.Cell;
2284     TargetParentFid.volume = TargetParentId.Volume;
2285     TargetParentFid.vnode  = TargetParentId.Vnode;
2286     TargetParentFid.unique = TargetParentId.Unique;
2287     TargetParentFid.hash   = TargetParentId.Hash;
2288
2289     code = cm_GetSCache(&SourceParentFid, NULL, &oldDscp, userp, &req);
2290     if (code) {
2291         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache source parent failed code 0x%x", 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         return;
2297     }
2298
2299     lock_ObtainWrite(&oldDscp->rw);
2300     code = cm_SyncOp(oldDscp, NULL, userp, &req, 0,
2301                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2302     if (code) {
2303         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp oldDscp 0x%p failed code 0x%x", oldDscp, code);
2304         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2305         if ( status == STATUS_INVALID_HANDLE)
2306             status = STATUS_OBJECT_PATH_INVALID;
2307         (*ResultCB)->ResultStatus = status;
2308         lock_ReleaseWrite(&oldDscp->rw);
2309         cm_ReleaseSCache(oldDscp);
2310         return;
2311     }
2312
2313     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2314     lock_ReleaseWrite(&oldDscp->rw);
2315
2316
2317     if (oldDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2318         osi_Log1(afsd_logp, "RDR_RenameFileEntry oldDscp 0x%p not a directory", oldDscp);
2319         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2320         cm_ReleaseSCache(oldDscp);
2321         return;
2322     }
2323
2324     code = cm_GetSCache(&TargetParentFid, NULL, &newDscp, userp, &req);
2325     if (code) {
2326         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target parent failed code 0x%x", code);
2327         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2328         (*ResultCB)->ResultStatus = status;
2329         cm_ReleaseSCache(oldDscp);
2330         return;
2331     }
2332
2333     lock_ObtainWrite(&newDscp->rw);
2334     code = cm_SyncOp(newDscp, NULL, userp, &req, 0,
2335                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2336     if (code) {
2337         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp newDscp 0x%p failed code 0x%x", newDscp, code);
2338         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2339         (*ResultCB)->ResultStatus = status;
2340         lock_ReleaseWrite(&newDscp->rw);
2341         cm_ReleaseSCache(oldDscp);
2342         cm_ReleaseSCache(newDscp);
2343         return;
2344     }
2345
2346     cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2347     lock_ReleaseWrite(&newDscp->rw);
2348
2349
2350     if (newDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2351         osi_Log1(afsd_logp, "RDR_RenameFileEntry newDscp 0x%p not a directory", newDscp);
2352         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2353         cm_ReleaseSCache(oldDscp);
2354         cm_ReleaseSCache(newDscp);
2355         return;
2356     }
2357
2358     /* Obtain the original FID just for debugging purposes */
2359     code = cm_BeginDirOp( oldDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2360     if (code == 0) {
2361         code = cm_BPlusDirLookup(&dirop, SourceFileName, &SourceFid);
2362         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2363         cm_EndDirOp(&dirop);
2364     }
2365
2366     code = cm_Rename( oldDscp, NULL, SourceFileName,
2367                       newDscp, TargetFileName, userp, &req);
2368     if (code == 0) {
2369         cm_scache_t *scp = 0;
2370         DWORD dwRemaining;
2371
2372         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2373         dwRemaining = ResultBufferLength - sizeof( AFSFileRenameResultCB) + sizeof( AFSDirEnumEntry);
2374         (*ResultCB)->ResultStatus = 0;
2375
2376         pResultCB->SourceParentDataVersion.QuadPart = oldDscp->dataVersion;
2377         pResultCB->TargetParentDataVersion.QuadPart = newDscp->dataVersion;
2378
2379         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p SUCCESS",
2380                  oldDscp, newDscp);
2381
2382         code = cm_BeginDirOp( newDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2383         if (code == 0) {
2384             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2385             cm_EndDirOp(&dirop);
2386         }
2387
2388         if (code != 0) {
2389             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_BPlusDirLookup failed code 0x%x",
2390                      code);
2391             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2392             cm_ReleaseSCache(oldDscp);
2393             cm_ReleaseSCache(newDscp);
2394             return;
2395         }
2396
2397         osi_Log4(afsd_logp, "RDR_RenameFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2398                   TargetFid.cell,  TargetFid.volume,
2399                   TargetFid.vnode, TargetFid.unique);
2400
2401         code = cm_GetSCache(&TargetFid, &newDscp->fid, &scp, userp, &req);
2402         if (code) {
2403             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target failed code 0x%x", code);
2404             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2405             (*ResultCB)->ResultStatus = status;
2406             cm_ReleaseSCache(oldDscp);
2407             cm_ReleaseSCache(newDscp);
2408             return;
2409         }
2410
2411         /* Make sure the source vnode is current */
2412         lock_ObtainWrite(&scp->rw);
2413         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2414                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2415         if (code) {
2416             osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp scp 0x%p failed code 0x%x", scp, code);
2417             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2418             (*ResultCB)->ResultStatus = status;
2419             lock_ReleaseWrite(&scp->rw);
2420             cm_ReleaseSCache(oldDscp);
2421             cm_ReleaseSCache(newDscp);
2422             cm_ReleaseSCache(scp);
2423             return;
2424         }
2425
2426         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2427         lock_ReleaseWrite(&scp->rw);
2428
2429         if (cm_shortNames) {
2430             dfid.vnode = htonl(scp->fid.vnode);
2431             dfid.unique = htonl(scp->fid.unique);
2432
2433             if (!cm_Is8Dot3(TargetFileName))
2434                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2435             else
2436                 shortName[0] = '\0';
2437         }
2438
2439         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2440                                  newDscp, scp, userp, &req, TargetFileName, shortName,
2441                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2442                                  0, NULL, &dwRemaining);
2443         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2444         cm_ReleaseSCache(scp);
2445
2446         osi_Log0(afsd_logp, "RDR_RenameFileEntry SUCCESS");
2447     } else {
2448         osi_Log3(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p failed code 0x%x",
2449                  oldDscp, newDscp, code);
2450         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2451         (*ResultCB)->ResultStatus = status;
2452         (*ResultCB)->ResultBufferLength = 0;
2453     }
2454
2455     cm_ReleaseSCache(oldDscp);
2456     cm_ReleaseSCache(newDscp);
2457     return;
2458 }
2459
2460 /*
2461  * AFS does not support cross-directory hard links but RDR_HardLinkFileEntry
2462  * is written as if AFS does.  The check for cross-directory links is
2463  * implemented in cm_Link().
2464  *
2465  * Windows supports optional ReplaceIfExists functionality.  The AFS file
2466  * server does not.  If the target name already exists and bReplaceIfExists
2467  * is true, check to see if the user has insert permission before calling
2468  * cm_Unlink() on the existing object.  If the user does not have insert
2469  * permission return STATUS_ACCESS_DENIED.
2470  */
2471
2472 void
2473 RDR_HardLinkFileEntry( IN cm_user_t *userp,
2474                        IN WCHAR    *SourceFileNameCounted,
2475                        IN DWORD     SourceFileNameLength,
2476                        IN AFSFileID SourceFileId,
2477                        IN AFSFileHardLinkCB *pHardLinkCB,
2478                        IN BOOL bWow64,
2479                        IN DWORD ResultBufferLength,
2480                        IN OUT AFSCommResult **ResultCB)
2481 {
2482
2483     AFSFileHardLinkResultCB *pResultCB = NULL;
2484     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2485     AFSFileID              SourceParentId   = pHardLinkCB->SourceParentId;
2486     AFSFileID              TargetParentId   = pHardLinkCB->TargetParentId;
2487     WCHAR *                TargetFileNameCounted = pHardLinkCB->TargetName;
2488     DWORD                  TargetFileNameLength = pHardLinkCB->TargetNameLength;
2489     cm_fid_t               SourceParentFid;
2490     cm_fid_t               TargetParentFid;
2491     cm_fid_t               SourceFid;
2492     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2493     cm_scache_t *          srcDscp = NULL;
2494     cm_scache_t *          targetDscp = NULL;
2495     cm_scache_t *          srcScp = NULL;
2496     cm_dirOp_t             dirop;
2497     wchar_t                shortName[13];
2498     wchar_t                SourceFileName[260];
2499     wchar_t                TargetFileName[260];
2500     cm_dirFid_t            dfid;
2501     cm_req_t               req;
2502     afs_uint32             code;
2503     DWORD                  status;
2504
2505     RDR_InitReq(&req, bWow64);
2506
2507     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2508     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2509
2510     osi_Log4(afsd_logp, "RDR_HardLinkFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2511               SourceParentId.Cell,  SourceParentId.Volume,
2512               SourceParentId.Vnode, SourceParentId.Unique);
2513     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2514     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2515               TargetParentId.Cell,  TargetParentId.Volume,
2516               TargetParentId.Vnode, TargetParentId.Unique);
2517     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2518
2519     *ResultCB = (AFSCommResult *)malloc( size);
2520     if (!(*ResultCB))
2521         return;
2522
2523     memset( *ResultCB,
2524             '\0',
2525             size);
2526
2527     pResultCB = (AFSFileHardLinkResultCB *)(*ResultCB)->ResultData;
2528
2529     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2530     {
2531         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry Invalid Name Length: src %u target %u",
2532                  SourceFileNameLength, TargetFileNameLength);
2533         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2534         return;
2535     }
2536
2537     SourceFid.cell   = SourceFileId.Cell;
2538     SourceFid.volume = SourceFileId.Volume;
2539     SourceFid.vnode  = SourceFileId.Vnode;
2540     SourceFid.unique = SourceFileId.Unique;
2541     SourceFid.hash   = SourceFileId.Hash;
2542
2543     SourceParentFid.cell   = SourceParentId.Cell;
2544     SourceParentFid.volume = SourceParentId.Volume;
2545     SourceParentFid.vnode  = SourceParentId.Vnode;
2546     SourceParentFid.unique = SourceParentId.Unique;
2547     SourceParentFid.hash   = SourceParentId.Hash;
2548
2549     TargetParentFid.cell   = TargetParentId.Cell;
2550     TargetParentFid.volume = TargetParentId.Volume;
2551     TargetParentFid.vnode  = TargetParentId.Vnode;
2552     TargetParentFid.unique = TargetParentId.Unique;
2553     TargetParentFid.hash   = TargetParentId.Hash;
2554
2555     code = cm_GetSCache(&SourceFid, NULL, &srcScp, userp, &req);
2556     if (code) {
2557         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache source failed code 0x%x", code);
2558         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2559         (*ResultCB)->ResultStatus = status;
2560         return;
2561     }
2562
2563     code = cm_GetSCache(&TargetParentFid, NULL, &targetDscp, userp, &req);
2564     if (code) {
2565         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache target parent failed code 0x%x", code);
2566         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2567         (*ResultCB)->ResultStatus = status;
2568         cm_ReleaseSCache(srcScp);
2569         return;
2570     }
2571
2572     lock_ObtainWrite(&targetDscp->rw);
2573     code = cm_SyncOp(targetDscp, NULL, userp, &req, PRSFS_INSERT,
2574                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2575     if (code) {
2576         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp targetDscp 0x%p failed code 0x%x", targetDscp, code);
2577         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2578         (*ResultCB)->ResultStatus = status;
2579         lock_ReleaseWrite(&targetDscp->rw);
2580         cm_ReleaseSCache(srcScp);
2581         cm_ReleaseSCache(targetDscp);
2582         return;
2583     }
2584
2585     cm_SyncOpDone(targetDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2586     lock_ReleaseWrite(&targetDscp->rw);
2587
2588     if (targetDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2589         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry targetDscp 0x%p not a directory", targetDscp);
2590         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2591         cm_ReleaseSCache(srcScp);
2592         cm_ReleaseSCache(targetDscp);
2593         return;
2594     }
2595
2596     if ( cm_FidCmp(&SourceParentFid, &TargetParentFid) ) {
2597         code = cm_GetSCache(&SourceParentFid, NULL, &srcDscp, userp, &req);
2598         if (code) {
2599             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache source parent failed code 0x%x", code);
2600             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2601             if ( status == STATUS_INVALID_HANDLE)
2602                 status = STATUS_OBJECT_PATH_INVALID;
2603             (*ResultCB)->ResultStatus = status;
2604             cm_ReleaseSCache(srcScp);
2605             cm_ReleaseSCache(targetDscp);
2606             return;
2607         }
2608
2609         lock_ObtainWrite(&srcDscp->rw);
2610         code = cm_SyncOp(srcDscp, NULL, userp, &req, 0,
2611                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2612         if (code) {
2613             osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp srcDscp 0x%p failed code 0x%x", srcDscp, code);
2614             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2615             if ( status == STATUS_INVALID_HANDLE)
2616                 status = STATUS_OBJECT_PATH_INVALID;
2617             (*ResultCB)->ResultStatus = status;
2618             lock_ReleaseWrite(&srcDscp->rw);
2619             if (srcDscp != targetDscp)
2620                 cm_ReleaseSCache(srcDscp);
2621             cm_ReleaseSCache(targetDscp);
2622             cm_ReleaseSCache(srcScp);
2623             return;
2624         }
2625
2626         cm_SyncOpDone(srcDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2627         lock_ReleaseWrite(&srcDscp->rw);
2628
2629         if (srcDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2630             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry srcDscp 0x%p not a directory", srcDscp);
2631             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2632             if (srcDscp != targetDscp)
2633                 cm_ReleaseSCache(srcDscp);
2634             cm_ReleaseSCache(targetDscp);
2635             cm_ReleaseSCache(srcScp);
2636             return;
2637         }
2638     } else {
2639         srcDscp = targetDscp;
2640     }
2641
2642     /* Obtain the target FID if it exists */
2643     code = cm_BeginDirOp( targetDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2644     if (code == 0) {
2645         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2646         cm_EndDirOp(&dirop);
2647     }
2648
2649     if (OrigTargetFid.vnode) {
2650
2651         /* An object exists with the target name */
2652         if (!pHardLinkCB->bReplaceIfExists) {
2653             osi_Log0(afsd_logp, "RDR_HardLinkFileEntry target name collision and !ReplaceIfExists");
2654             (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_COLLISION;
2655             if (srcDscp != targetDscp)
2656                 cm_ReleaseSCache(srcDscp);
2657             cm_ReleaseSCache(targetDscp);
2658             cm_ReleaseSCache(srcScp);
2659             return;
2660         }
2661
2662         lock_ObtainWrite(&targetDscp->rw);
2663         code = cm_SyncOp(targetDscp, NULL, userp, &req, PRSFS_INSERT | PRSFS_DELETE,
2664                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2665         if (code) {
2666             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2667             (*ResultCB)->ResultStatus = status;
2668             lock_ReleaseWrite(&srcDscp->rw);
2669             if (srcDscp != targetDscp)
2670                 cm_ReleaseSCache(srcDscp);
2671             cm_ReleaseSCache(targetDscp);
2672             cm_ReleaseSCache(srcScp);
2673             return;
2674         }
2675         cm_SyncOpDone(targetDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2676         lock_ReleaseWrite(&targetDscp->rw);
2677
2678         code = cm_Unlink(targetDscp, NULL, TargetFileName, userp, &req);
2679         if (code) {
2680             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_Unlink code 0x%x", code);
2681             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2682             (*ResultCB)->ResultStatus = status;
2683             lock_ReleaseWrite(&srcDscp->rw);
2684             if (srcDscp != targetDscp)
2685                 cm_ReleaseSCache(srcDscp);
2686             cm_ReleaseSCache(targetDscp);
2687             cm_ReleaseSCache(srcScp);
2688             return;
2689         }
2690     }
2691
2692     code = cm_Link( targetDscp, TargetFileName, srcScp, 0, userp, &req);
2693     if (code == 0) {
2694         cm_fid_t TargetFid;
2695         cm_scache_t *targetScp = 0;
2696         DWORD dwRemaining;
2697
2698         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2699         dwRemaining = ResultBufferLength - sizeof( AFSFileHardLinkResultCB) + sizeof( AFSDirEnumEntry);
2700         (*ResultCB)->ResultStatus = 0;
2701
2702         pResultCB->SourceParentDataVersion.QuadPart = srcDscp->dataVersion;
2703         pResultCB->TargetParentDataVersion.QuadPart = targetDscp->dataVersion;
2704
2705         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_Link srcDscp 0x%p targetDscp 0x%p SUCCESS",
2706                  srcDscp, targetDscp);
2707
2708         code = cm_BeginDirOp( targetDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2709         if (code == 0) {
2710             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2711             cm_EndDirOp(&dirop);
2712         }
2713
2714         if (code != 0) {
2715             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_BPlusDirLookup failed code 0x%x",
2716                      code);
2717             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2718             if (srcDscp != targetDscp)
2719                 cm_ReleaseSCache(srcDscp);
2720             cm_ReleaseSCache(srcScp);
2721             cm_ReleaseSCache(targetDscp);
2722             return;
2723         }
2724
2725         osi_Log4(afsd_logp, "RDR_HardLinkFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2726                   TargetFid.cell,  TargetFid.volume,
2727                   TargetFid.vnode, TargetFid.unique);
2728
2729         code = cm_GetSCache(&TargetFid, &targetDscp->fid, &targetScp, userp, &req);
2730         if (code) {
2731             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache target failed code 0x%x", code);
2732             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2733             (*ResultCB)->ResultStatus = status;
2734             if (srcDscp != targetDscp)
2735                 cm_ReleaseSCache(srcDscp);
2736             cm_ReleaseSCache(srcScp);
2737             cm_ReleaseSCache(targetDscp);
2738             return;
2739         }
2740
2741         /* Make sure the source vnode is current */
2742         lock_ObtainWrite(&targetScp->rw);
2743         code = cm_SyncOp(targetScp, NULL, userp, &req, 0,
2744                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2745         if (code) {
2746             osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp scp 0x%p failed code 0x%x",
2747                      targetScp, code);
2748             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2749             (*ResultCB)->ResultStatus = status;
2750             lock_ReleaseWrite(&targetScp->rw);
2751             cm_ReleaseSCache(targetScp);
2752             if (srcDscp != targetDscp)
2753                 cm_ReleaseSCache(srcDscp);
2754             cm_ReleaseSCache(srcScp);
2755             cm_ReleaseSCache(targetDscp);
2756             return;
2757         }
2758
2759         cm_SyncOpDone(targetScp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2760         lock_ReleaseWrite(&targetScp->rw);
2761
2762         if (cm_shortNames) {
2763             dfid.vnode = htonl(targetScp->fid.vnode);
2764             dfid.unique = htonl(targetScp->fid.unique);
2765
2766             if (!cm_Is8Dot3(TargetFileName))
2767                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2768             else
2769                 shortName[0] = '\0';
2770         }
2771
2772         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2773                                  targetDscp, targetScp, userp, &req, TargetFileName, shortName,
2774                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2775                                  0, NULL, &dwRemaining);
2776         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2777         cm_ReleaseSCache(targetScp);
2778
2779         osi_Log0(afsd_logp, "RDR_HardLinkFileEntry SUCCESS");
2780     } else {
2781         osi_Log3(afsd_logp, "RDR_HardLinkFileEntry cm_Link srcDscp 0x%p targetDscp 0x%p failed code 0x%x",
2782                  srcDscp, targetDscp, code);
2783         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2784         (*ResultCB)->ResultStatus = status;
2785         (*ResultCB)->ResultBufferLength = 0;
2786     }
2787
2788     cm_ReleaseSCache(srcScp);
2789     if (srcDscp != targetDscp)
2790         cm_ReleaseSCache(srcDscp);
2791     cm_ReleaseSCache(targetDscp);
2792     return;
2793 }
2794
2795 void
2796 RDR_FlushFileEntry( IN cm_user_t *userp,
2797                     IN AFSFileID FileId,
2798                     IN BOOL bWow64,
2799                     IN DWORD ResultBufferLength,
2800                     IN OUT AFSCommResult **ResultCB)
2801 {
2802     cm_scache_t *scp = NULL;
2803     cm_fid_t    Fid;
2804     afs_uint32  code;
2805     cm_req_t    req;
2806     DWORD       status;
2807 #ifdef ODS_DEBUG
2808     char        dbgstr[1024];
2809 #endif
2810
2811     RDR_InitReq(&req, bWow64);
2812
2813     osi_Log4(afsd_logp, "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x",
2814               FileId.Cell, FileId.Volume,
2815               FileId.Vnode, FileId.Unique);
2816 #ifdef ODS_DEBUG
2817     snprintf( dbgstr, 1024,
2818               "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x\n",
2819               FileId.Cell, FileId.Volume,
2820               FileId.Vnode, FileId.Unique);
2821     OutputDebugStringA( dbgstr);
2822 #endif
2823
2824     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2825     if (!(*ResultCB)) {
2826         osi_Log0(afsd_logp, "RDR_FlushFileEntry out of memory");
2827         return;
2828     }
2829
2830     memset( *ResultCB,
2831             '\0',
2832             sizeof( AFSCommResult));
2833
2834     /* Process the release */
2835     Fid.cell = FileId.Cell;
2836     Fid.volume = FileId.Volume;
2837     Fid.vnode = FileId.Vnode;
2838     Fid.unique = FileId.Unique;
2839     Fid.hash = FileId.Hash;
2840
2841     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2842     if (code) {
2843         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2844         (*ResultCB)->ResultStatus = status;
2845         osi_Log2(afsd_logp, "RDR_FlushFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2846                   code, status);
2847         return;
2848     }
2849
2850     lock_ObtainWrite(&scp->rw);
2851     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2852         lock_ReleaseWrite(&scp->rw);
2853         (*ResultCB)->ResultStatus = STATUS_INVALID_HANDLE;
2854         return;
2855     }
2856
2857     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2858                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2859     if (code) {
2860         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2861         (*ResultCB)->ResultStatus = status;
2862         lock_ReleaseWrite(&scp->rw);
2863         cm_ReleaseSCache(scp);
2864         osi_Log3(afsd_logp, "RDR_FlushFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2865                  scp, code, status);
2866         return;
2867     }
2868
2869     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2870     lock_ReleaseWrite(&scp->rw);
2871
2872     code = cm_FSync(scp, userp, &req, FALSE);
2873     cm_ReleaseSCache(scp);
2874
2875     if (code) {
2876         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2877         (*ResultCB)->ResultStatus = status;
2878         osi_Log2(afsd_logp, "RDR_FlushFileEntry FAILURE code=0x%x status=0x%x",
2879                   code, status);
2880     } else {
2881         (*ResultCB)->ResultStatus = 0;
2882         osi_Log0(afsd_logp, "RDR_FlushFileEntry SUCCESS");
2883     }
2884     (*ResultCB)->ResultBufferLength = 0;
2885
2886     return;
2887 }
2888
2889 afs_uint32
2890 RDR_CheckAccess( IN cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
2891                  ULONG access,
2892                  ULONG *granted)
2893 {
2894     ULONG afs_acc, afs_gr;
2895     BOOLEAN file, dir;
2896     afs_uint32 code = 0;
2897
2898     file = (scp->fileType == CM_SCACHETYPE_FILE);
2899     dir = !file;
2900
2901     /* access definitions from prs_fs.h */
2902     afs_acc = 0;
2903     if (access & FILE_READ_DATA)
2904         afs_acc |= PRSFS_READ;
2905     if (access & FILE_READ_EA || access & FILE_READ_ATTRIBUTES)
2906         afs_acc |= PRSFS_READ;
2907     if (file && ((access & FILE_WRITE_DATA) || (access & FILE_APPEND_DATA)))
2908         afs_acc |= PRSFS_WRITE;
2909     if (access & FILE_WRITE_EA || access & FILE_WRITE_ATTRIBUTES)
2910         afs_acc |= PRSFS_WRITE;
2911     if (dir && ((access & FILE_ADD_FILE) || (access & FILE_ADD_SUBDIRECTORY)))
2912         afs_acc |= PRSFS_INSERT;
2913     if (dir && (access & FILE_LIST_DIRECTORY))
2914         afs_acc |= PRSFS_LOOKUP;
2915     if (file && (access & FILE_EXECUTE))
2916         afs_acc |= PRSFS_WRITE;
2917     if (dir && (access & FILE_TRAVERSE))
2918         afs_acc |= PRSFS_READ;
2919     if (dir && (access & FILE_DELETE_CHILD))
2920         afs_acc |= PRSFS_DELETE;
2921     if ((access & DELETE))
2922         afs_acc |= PRSFS_DELETE;
2923
2924     /* check ACL with server */
2925     lock_ObtainWrite(&scp->rw);
2926     while (1)
2927     {
2928         if (cm_HaveAccessRights(scp, userp, reqp, afs_acc, &afs_gr))
2929         {
2930             break;
2931         }
2932         else
2933         {
2934             /* we don't know the required access rights */
2935             code = cm_GetAccessRights(scp, userp, reqp);
2936             if (code)
2937                 break;
2938             continue;
2939         }
2940     }
2941     lock_ReleaseWrite(&(scp->rw));
2942
2943     if (code == 0) {
2944         *granted = 0;
2945         if (afs_gr & PRSFS_READ)
2946             *granted |= FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_EXECUTE;
2947         if (afs_gr & PRSFS_WRITE)
2948             *granted |= FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_EXECUTE;
2949         if (afs_gr & PRSFS_INSERT)
2950             *granted |= (dir ? FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY : 0) | (file ? FILE_ADD_SUBDIRECTORY : 0);
2951         if (afs_gr & PRSFS_LOOKUP)
2952             *granted |= (dir ? FILE_LIST_DIRECTORY : 0);
2953         if (afs_gr & PRSFS_DELETE)
2954             *granted |= FILE_DELETE_CHILD | DELETE;
2955         if (afs_gr & PRSFS_LOCK)
2956             *granted |= 0;
2957         if (afs_gr & PRSFS_ADMINISTER)
2958             *granted |= 0;
2959
2960         *granted |= SYNCHRONIZE | READ_CONTROL;
2961
2962         /* don't give more access than what was requested */
2963         *granted &= access;
2964         osi_Log3(afsd_logp, "RDR_CheckAccess SUCCESS scp=0x%p requested=0x%x granted=0x%x", scp, access, *granted);
2965     } else
2966         osi_Log2(afsd_logp, "RDR_CheckAccess FAILURE scp=0x%p code=0x%x",
2967                  scp, code);
2968
2969     return code;
2970 }
2971
2972 void
2973 RDR_OpenFileEntry( IN cm_user_t *userp,
2974                    IN AFSFileID FileId,
2975                    IN AFSFileOpenCB *OpenCB,
2976                    IN BOOL bWow64,
2977                    IN BOOL bHoldFid,
2978                    IN DWORD ResultBufferLength,
2979                    IN OUT AFSCommResult **ResultCB)
2980 {
2981     AFSFileOpenResultCB *pResultCB = NULL;
2982     cm_scache_t *scp = NULL;
2983     cm_user_t   *sysUserp = NULL;
2984     cm_fid_t    Fid;
2985     cm_lock_data_t      *ldp = NULL;
2986     afs_uint32  code;
2987     cm_req_t    req;
2988     DWORD       status;
2989
2990     RDR_InitReq(&req, bWow64);
2991
2992     osi_Log4(afsd_logp, "RDR_OpenFileEntry File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2993               FileId.Cell, FileId.Volume,
2994               FileId.Vnode, FileId.Unique);
2995
2996     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2997     if (!(*ResultCB)) {
2998         osi_Log0(afsd_logp, "RDR_OpenFileEntry out of memory");
2999         return;
3000     }
3001
3002     memset( *ResultCB,
3003             '\0',
3004             sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
3005
3006     pResultCB = (AFSFileOpenResultCB *)(*ResultCB)->ResultData;
3007
3008     /* Process the release */
3009     Fid.cell = FileId.Cell;
3010     Fid.volume = FileId.Volume;
3011     Fid.vnode = FileId.Vnode;
3012     Fid.unique = FileId.Unique;
3013     Fid.hash = FileId.Hash;
3014
3015     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3016     if (code) {
3017         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3018         (*ResultCB)->ResultStatus = status;
3019         osi_Log2(afsd_logp, "RDR_OpenFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
3020                   code, status);
3021         return;
3022     }
3023
3024     lock_ObtainWrite(&scp->rw);
3025     code = cm_SyncOp(scp, NULL, userp, &req, 0,
3026                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3027     if (code) {
3028         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3029         (*ResultCB)->ResultStatus = status;
3030         lock_ReleaseWrite(&scp->rw);
3031         cm_ReleaseSCache(scp);
3032         osi_Log3(afsd_logp, "RDR_OpenFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
3033                  scp, code, status);
3034         return;
3035     }
3036
3037     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3038     lock_ReleaseWrite(&scp->rw);
3039
3040     sysUserp = RDR_GetLocalSystemUser();
3041
3042     /*
3043      * Skip the open check if the request is coming from the local system account.
3044      * The local system has no tokens and therefore any requests sent to a file
3045      * server will fail.  Unfortunately, there are special system processes that
3046      * perform actions on files and directories in preparation for memory mapping
3047      * executables.  If the open check fails, the real request from the user process
3048      * will never be issued.
3049      *
3050      * Permitting the file system to allow subsequent operations to proceed does
3051      * not compromise security.  All requests to obtain file data or directory
3052      * enumerations will subsequently fail if they are not submitted under the
3053      * context of a process for that have access to the necessary credentials.
3054      */
3055
3056     if ( userp == sysUserp)
3057     {
3058         osi_Log1(afsd_logp, "RDR_OpenFileEntry LOCAL_SYSTEM access check skipped scp=0x%p",
3059                  scp);
3060         pResultCB->GrantedAccess = OpenCB->DesiredAccess;
3061         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3062         code = 0;
3063     }
3064     else
3065     {
3066         int count = 0;
3067
3068         do {
3069             if (count++ > 0) {
3070                 Sleep(350);
3071                 osi_Log3(afsd_logp,
3072                          "RDR_OpenFileEntry repeating open check scp=0x%p userp=0x%p code=0x%x",
3073                          scp, userp, code);
3074             }
3075             code = cm_CheckNTOpen(scp, OpenCB->DesiredAccess, OpenCB->ShareAccess,
3076                                   OPEN_ALWAYS,
3077                                   OpenCB->ProcessId, OpenCB->Identifier,
3078                                   userp, &req, &ldp);
3079             if (code == 0)
3080                 code = RDR_CheckAccess(scp, userp, &req, OpenCB->DesiredAccess, &pResultCB->GrantedAccess);
3081             cm_CheckNTOpenDone(scp, userp, &req, &ldp);
3082         } while (count < 100 && (code == CM_ERROR_RETRY || code == CM_ERROR_WOULDBLOCK));
3083     }
3084
3085     /*
3086      * If we are restricting sharing, we should do so with a suitable
3087      * share lock.
3088      */
3089     if (code == 0 && scp->fileType == CM_SCACHETYPE_FILE && !(OpenCB->ShareAccess & FILE_SHARE_WRITE)) {
3090         cm_key_t key;
3091         LARGE_INTEGER LOffset, LLength;
3092         int sLockType;
3093
3094         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
3095         LOffset.LowPart = SMB_FID_QLOCK_LOW;
3096         LLength.HighPart = 0;
3097         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
3098
3099         /*
3100          * If we are not opening the file for writing, then we don't
3101          * try to get an exclusive lock.  No one else should be able to
3102          * get an exclusive lock on the file anyway, although someone
3103          * else can get a shared lock.
3104          */
3105         if ((OpenCB->ShareAccess & FILE_SHARE_READ) || !(OpenCB->DesiredAccess & AFS_ACCESS_WRITE))
3106         {
3107             sLockType = LOCKING_ANDX_SHARED_LOCK;
3108         } else {
3109             sLockType = 0;
3110         }
3111
3112         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, OpenCB->Identifier);
3113
3114         lock_ObtainWrite(&scp->rw);
3115         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, &req, NULL);
3116         lock_ReleaseWrite(&scp->rw);
3117
3118         if (code) {
3119             code = CM_ERROR_SHARING_VIOLATION;
3120             pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3121         } else {
3122             if (sLockType == LOCKING_ANDX_SHARED_LOCK)
3123                 pResultCB->FileAccess = AFS_FILE_ACCESS_SHARED;
3124             else
3125                 pResultCB->FileAccess = AFS_FILE_ACCESS_EXCLUSIVE;
3126         }
3127     } else {
3128         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3129     }
3130
3131     cm_ReleaseUser(sysUserp);
3132     if (code == 0 && bHoldFid)
3133         RDR_FlagScpInUse( scp, FALSE );
3134     cm_ReleaseSCache(scp);
3135
3136     if (code) {
3137         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3138         (*ResultCB)->ResultStatus = status;
3139         osi_Log2(afsd_logp, "RDR_OpenFileEntry FAILURE code=0x%x status=0x%x",
3140                   code, status);
3141     } else {
3142         (*ResultCB)->ResultStatus = 0;
3143         (*ResultCB)->ResultBufferLength = sizeof( AFSFileOpenResultCB);
3144         osi_Log0(afsd_logp, "RDR_OpenFileEntry SUCCESS");
3145     }
3146     return;
3147 }
3148
3149 void
3150 RDR_ReleaseFileAccess( IN cm_user_t *userp,
3151                        IN AFSFileID FileId,
3152                        IN AFSFileAccessReleaseCB *ReleaseFileCB,
3153                        IN BOOL bWow64,
3154                        IN DWORD ResultBufferLength,
3155                        IN OUT AFSCommResult **ResultCB)
3156 {
3157     cm_key_t key;
3158     unsigned int sLockType;
3159     LARGE_INTEGER LOffset, LLength;
3160     cm_scache_t *scp = NULL;
3161     cm_fid_t    Fid;
3162     afs_uint32  code;
3163     cm_req_t    req;
3164     DWORD       status;
3165
3166     RDR_InitReq(&req, bWow64);
3167
3168     osi_Log4(afsd_logp, "RDR_ReleaseFileAccess File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3169               FileId.Cell, FileId.Volume,
3170               FileId.Vnode, FileId.Unique);
3171
3172     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
3173     if (!(*ResultCB)) {
3174         osi_Log0(afsd_logp, "RDR_ReleaseFileAccess out of memory");
3175         return;
3176     }
3177
3178     memset( *ResultCB, '\0', sizeof( AFSCommResult));
3179
3180     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_NOLOCK)
3181         return;
3182
3183     /* Process the release */
3184     Fid.cell = FileId.Cell;
3185     Fid.volume = FileId.Volume;
3186     Fid.vnode = FileId.Vnode;
3187     Fid.unique = FileId.Unique;
3188     Fid.hash = FileId.Hash;
3189
3190     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3191     if (code) {
3192         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3193         (*ResultCB)->ResultStatus = status;
3194         osi_Log2(afsd_logp, "RDR_ReleaseFileAccess cm_GetSCache FID failure code=0x%x status=0x%x",
3195                   code, status);
3196         return;
3197     }
3198
3199     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_SHARED)
3200         sLockType = LOCKING_ANDX_SHARED_LOCK;
3201     else
3202         sLockType = 0;
3203
3204     key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, ReleaseFileCB->Identifier);
3205
3206     LOffset.HighPart = SMB_FID_QLOCK_HIGH;
3207     LOffset.LowPart = SMB_FID_QLOCK_LOW;
3208     LLength.HighPart = 0;
3209     LLength.LowPart = SMB_FID_QLOCK_LENGTH;
3210
3211     lock_ObtainWrite(&scp->rw);
3212
3213     code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
3214     if (code == 0)
3215     {
3216         code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
3217
3218         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
3219
3220         if (code == CM_ERROR_RANGE_NOT_LOCKED)
3221         {
3222             osi_Log3(afsd_logp, "RDR_ReleaseFileAccess Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
3223                      ReleaseFileCB->FileAccess, ReleaseFileCB->ProcessId, ReleaseFileCB->Identifier);
3224         }
3225     }
3226
3227     lock_ReleaseWrite(&scp->rw);
3228
3229     osi_Log0(afsd_logp, "RDR_ReleaseFileAccessEntry SUCCESS");
3230 }
3231
3232 static const char *
3233 HexCheckSum(unsigned char * buf, int buflen, unsigned char * md5cksum)
3234 {
3235     int i, k;
3236     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
3237
3238     if (buflen < 33)
3239         return "buffer length too small to HexCheckSum";
3240
3241     for (i=0;i<16;i++) {
3242         k = md5cksum[i];
3243
3244         buf[i*2] = tr[k / 16];
3245         buf[i*2+1] = tr[k % 16];
3246     }
3247     buf[32] = '\0';
3248
3249     return buf;
3250 }
3251
3252 /*
3253  * Extent requests from the file system are triggered when a file
3254  * page is not resident in the Windows cache.  The file system is
3255  * responsible for loading the page but cannot block the request
3256  * while doing so.  The AFS Redirector forwards the requests to
3257  * the AFS cache manager while indicating to Windows that the page
3258  * is not yet available.  A polling operation will then ensue with
3259  * the AFS Redirector issuing a RDR_RequestFileExtentsXXX call for
3260  * each poll attempt.  As each request is received and processed
3261  * by a separate worker thread in the service, this can lead to
3262  * contention by multiple threads attempting to claim the same
3263  * cm_buf_t objects.  Therefore, it is important that
3264  *
3265  *  (a) the service avoid processing more than one overlapping
3266  *      extent request at a time
3267  *  (b) background daemon processing be used to avoid blocking
3268  *      of ioctl threads
3269  *
3270  * Beginning with the 20091122 build of the redirector, the redirector
3271  * will not issue an additional RDR_RequestFileExtentsXXX call for
3272  * each poll request.  Instead, afsd_service is required to track
3273  * the requests and return them to the redirector or fail the
3274  * portions of the request that cannot be satisfied.
3275  *
3276  * The request processing returns any extents that can be returned
3277  * immediately to the redirector.  The rest of the requested range(s)
3278  * are queued as background operations using RDR_BkgFetch().
3279  */
3280
3281 /* do the background fetch. */
3282 afs_int32
3283 RDR_BkgFetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
3284              cm_user_t *userp, cm_req_t *reqp)
3285 {
3286     osi_hyper_t length;
3287     osi_hyper_t base;
3288     osi_hyper_t offset;
3289     osi_hyper_t end;
3290     osi_hyper_t fetched;
3291     osi_hyper_t tblocksize;
3292     afs_int32 code;
3293     int rwheld = 0;
3294     cm_buf_t *bufp = NULL;
3295     DWORD dwResultBufferLength;
3296     AFSSetFileExtentsCB *pResultCB;
3297     DWORD status;
3298     afs_uint32 count=0;
3299     AFSFileID FileId;
3300     int reportErrorToRedir = 0;
3301     int force_retry = 0;
3302
3303     FileId.Cell = scp->fid.cell;
3304     FileId.Volume = scp->fid.volume;
3305     FileId.Vnode = scp->fid.vnode;
3306     FileId.Unique = scp->fid.unique;
3307     FileId.Hash = scp->fid.hash;
3308
3309     fetched.LowPart = 0;
3310     fetched.HighPart = 0;
3311     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
3312     base.LowPart = p1;
3313     base.HighPart = p2;
3314     length.LowPart = p3;
3315     length.HighPart = p4;
3316
3317     end = LargeIntegerAdd(base, length);
3318
3319     osi_Log5(afsd_logp, "Starting BKG Fetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
3320              scp, p2, p1, p4, p3);
3321
3322     /*
3323      * Make sure we have a callback.
3324      * This is necessary so that we can return access denied
3325      * if a callback cannot be granted.
3326      */
3327     lock_ObtainWrite(&scp->rw);
3328     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_READ,
3329                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3330     if (code) {
3331         lock_ReleaseWrite(&scp->rw);
3332         osi_Log2(afsd_logp, "RDR_BkgFetch cm_SyncOp failure scp=0x%p code=0x%x",
3333                  scp, code);
333