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