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