2eaa3a1392c4c48affb0ce8dc604eeba33f2c3e4
[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                 cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_ASYNCSTORE);
1870
1871                 code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
1872                                  CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1873                 /*
1874                  * If we only have 'i' bits, then we should still be able to
1875                  * set flush the file.
1876                  */
1877                 if (code == CM_ERROR_NOACCESS && scp->creator == userp) {
1878                     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_INSERT,
1879                                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1880                 }
1881                 if (code == 0) {
1882                     if (bScpLocked) {
1883                         lock_ReleaseWrite(&scp->rw);
1884                         bScpLocked = FALSE;
1885                     }
1886
1887                     code = cm_FSync(scp, userp, &req, bScpLocked);
1888                 }
1889             }
1890             if (bLastHandle && code)
1891                 goto unlock;
1892         }
1893
1894         if (CleanupCB->ChangeTime.QuadPart) {
1895
1896             if (scp->fileType == CM_SCACHETYPE_FILE) {
1897                 /* Do not set length and other attributes at the same time */
1898                 if (scp->length.QuadPart != CleanupCB->AllocationSize.QuadPart) {
1899                     osi_Log2(afsd_logp, "RDR_CleanupFileEntry Length Change 0x%x -> 0x%x",
1900                              (afs_uint32)scp->length.QuadPart, (afs_uint32)CleanupCB->AllocationSize.QuadPart);
1901                     setAttr.mask |= CM_ATTRMASK_LENGTH;
1902                     setAttr.length.LowPart = CleanupCB->AllocationSize.LowPart;
1903                     setAttr.length.HighPart = CleanupCB->AllocationSize.HighPart;
1904
1905                     if (bScpLocked) {
1906                         lock_ReleaseWrite(&scp->rw);
1907                         bScpLocked = FALSE;
1908                     }
1909                     code = cm_SetAttr(scp, &setAttr, userp, &req);
1910                     if (code)
1911                         goto unlock;
1912                     setAttr.mask = 0;
1913                 }
1914             }
1915
1916             if (!bScpLocked) {
1917                 lock_ObtainWrite(&scp->rw);
1918                 bScpLocked = TRUE;
1919             }
1920
1921             if ((scp->unixModeBits & 0200) && (CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1922                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1923                 setAttr.unixModeBits = scp->unixModeBits & ~0222;
1924             } else if (!(scp->unixModeBits & 0200) && !(CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1925                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1926                 setAttr.unixModeBits = scp->unixModeBits | 0222;
1927             }
1928         }
1929
1930         if (CleanupCB->LastWriteTime.QuadPart) {
1931             ft.dwLowDateTime = CleanupCB->LastWriteTime.LowPart;
1932             ft.dwHighDateTime = CleanupCB->LastWriteTime.HighPart;
1933
1934             cm_UnixTimeFromLargeSearchTime(&clientModTime, &ft);
1935             if (scp->clientModTime != clientModTime) {
1936                 setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1937                 setAttr.clientModTime = clientModTime;
1938             }
1939         }
1940
1941         /* call setattr */
1942         if (setAttr.mask) {
1943             if (bScpLocked) {
1944                 lock_ReleaseWrite(&scp->rw);
1945                 bScpLocked = FALSE;
1946             }
1947             code = cm_SetAttr(scp, &setAttr, userp, &req);
1948         } else
1949             code = 0;
1950     }
1951
1952   unlock:
1953     /* Now drop the lock enforcing the share access */
1954     if ( CleanupCB->FileAccess != AFS_FILE_ACCESS_NOLOCK) {
1955         unsigned int sLockType;
1956         LARGE_INTEGER LOffset, LLength;
1957
1958         if (CleanupCB->FileAccess == AFS_FILE_ACCESS_SHARED)
1959             sLockType = LOCKING_ANDX_SHARED_LOCK;
1960         else
1961             sLockType = 0;
1962
1963         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, CleanupCB->Identifier);
1964
1965         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
1966         LOffset.LowPart = SMB_FID_QLOCK_LOW;
1967         LLength.HighPart = 0;
1968         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
1969
1970         if (!bScpLocked) {
1971             lock_ObtainWrite(&scp->rw);
1972             bScpLocked = TRUE;
1973         }
1974
1975         code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
1976         if (code == 0)
1977         {
1978             code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
1979
1980             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
1981
1982             if (code == CM_ERROR_RANGE_NOT_LOCKED)
1983             {
1984                 osi_Log3(afsd_logp, "RDR_CleanupFileEntry Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
1985                          CleanupCB->FileAccess, CleanupCB->ProcessId, CleanupCB->Identifier);
1986
1987             }
1988         }
1989     }
1990
1991     if (bUnlockFile || bDeleteFile) {
1992         if (!bScpLocked) {
1993             lock_ObtainWrite(&scp->rw);
1994             bScpLocked = TRUE;
1995         }
1996         code = cm_SyncOp(scp, NULL, userp, &req, 0,
1997                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1998         if (code) {
1999             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp (2) failure scp=0x%p code=0x%x",
2000                      scp, code);
2001             goto on_error;
2002         }
2003
2004         key = cm_GenerateKey(CM_SESSION_IFS, CleanupCB->ProcessId, 0);
2005
2006         /* the scp is now locked and current */
2007         code = cm_UnlockByKey(scp, key,
2008                               bDeleteFile ? CM_UNLOCK_FLAG_BY_FID : 0,
2009                               userp, &req);
2010
2011         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2012
2013         if (code)
2014             goto on_error;
2015     }
2016
2017   on_error:
2018     if (bDscpLocked)
2019         lock_ReleaseWrite(&dscp->rw);
2020     if (bScpLocked)
2021         lock_ReleaseWrite(&scp->rw);
2022
2023     if (code == 0 && dscp && bDeleteFile) {
2024         WCHAR FileName[260];
2025
2026         StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2027
2028         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2029             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2030         else
2031             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2032     }
2033
2034     if (code == 0) {
2035         if ( ResultBufferLength >=  sizeof( AFSFileCleanupResultCB))
2036         {
2037             (*ResultCB)->ResultBufferLength = sizeof( AFSFileCleanupResultCB);
2038             pResultCB = (AFSFileCleanupResultCB *)&(*ResultCB)->ResultData;
2039             pResultCB->ParentDataVersion.QuadPart = dscp ? dscp->dataVersion : 0;
2040         } else {
2041             (*ResultCB)->ResultBufferLength = 0;
2042         }
2043
2044         (*ResultCB)->ResultStatus = 0;
2045         osi_Log0(afsd_logp, "RDR_CleanupFileEntry SUCCESS");
2046     } else {
2047         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2048         (*ResultCB)->ResultStatus = status;
2049         osi_Log2(afsd_logp, "RDR_CleanupFileEntry FAILURE code=0x%x status=0x%x",
2050                   code, status);
2051     }
2052
2053     if (scp)
2054         cm_ReleaseSCache(scp);
2055     if (dscp)
2056         cm_ReleaseSCache(dscp);
2057
2058     return;
2059 }
2060
2061 void
2062 RDR_DeleteFileEntry( IN cm_user_t *userp,
2063                      IN AFSFileID ParentId,
2064                      IN ULONGLONG ProcessId,
2065                      IN WCHAR *FileNameCounted,
2066                      IN DWORD FileNameLength,
2067                      IN BOOL bWow64,
2068                      IN BOOL bCheckOnly,
2069                      IN DWORD ResultBufferLength,
2070                      IN OUT AFSCommResult **ResultCB)
2071 {
2072
2073     AFSFileDeleteResultCB *pResultCB = NULL;
2074     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2075     cm_fid_t            parentFid;
2076     afs_uint32          code;
2077     cm_scache_t *       dscp = NULL;
2078     cm_scache_t *       scp = NULL;
2079     afs_uint32          flags = 0;
2080     cm_attr_t           setAttr;
2081     cm_req_t            req;
2082     DWORD               status;
2083     wchar_t             FileName[260];
2084     cm_key_t            key;
2085
2086     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2087
2088     osi_Log4(afsd_logp, "RDR_DeleteFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2089               ParentId.Cell,  ParentId.Volume,
2090               ParentId.Vnode, ParentId.Unique);
2091     osi_Log2(afsd_logp, "... name=%S checkOnly=%x",
2092              osi_LogSaveStringW(afsd_logp, FileName),
2093              bCheckOnly);
2094
2095     RDR_InitReq(&req, bWow64);
2096     memset(&setAttr, 0, sizeof(cm_attr_t));
2097
2098     *ResultCB = (AFSCommResult *)malloc( size);
2099     if (!(*ResultCB)) {
2100         osi_Log0(afsd_logp, "RDR_DeleteFileEntry out of memory");
2101         return;
2102     }
2103
2104     memset( *ResultCB,
2105             '\0',
2106             size);
2107
2108     parentFid.cell   = ParentId.Cell;
2109     parentFid.volume = ParentId.Volume;
2110     parentFid.vnode  = ParentId.Vnode;
2111     parentFid.unique = ParentId.Unique;
2112     parentFid.hash   = ParentId.Hash;
2113
2114     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
2115     if (code) {
2116         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2117         if ( status == STATUS_INVALID_HANDLE)
2118             status = STATUS_OBJECT_PATH_INVALID;
2119         (*ResultCB)->ResultStatus = status;
2120         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
2121                   code, status);
2122         return;
2123     }
2124
2125     lock_ObtainWrite(&dscp->rw);
2126
2127     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
2128                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2129     if (code) {
2130         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2131         (*ResultCB)->ResultStatus = status;
2132         (*ResultCB)->ResultBufferLength = 0;
2133         lock_ReleaseWrite(&dscp->rw);
2134         cm_ReleaseSCache(dscp);
2135         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
2136                  dscp, code, status);
2137         return;
2138     }
2139
2140     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2141     lock_ReleaseWrite(&dscp->rw);
2142
2143     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2144         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2145         cm_ReleaseSCache(dscp);
2146         osi_Log1(afsd_logp, "RDR_DeleteFileEntry Not a Directory dscp=0x%p",
2147                  dscp);
2148         return;
2149     }
2150
2151     code = cm_Lookup(dscp, FileName, 0, userp, &req, &scp);
2152     if (code) {
2153         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2154         (*ResultCB)->ResultStatus = status;
2155         (*ResultCB)->ResultBufferLength = 0;
2156         cm_ReleaseSCache(dscp);
2157         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_Lookup failure code=0x%x status=0x%x",
2158                  code, status);
2159         return;
2160     }
2161
2162     lock_ObtainWrite(&scp->rw);
2163     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_DELETE,
2164                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2165     if (code) {
2166         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2167         (*ResultCB)->ResultStatus = status;
2168         (*ResultCB)->ResultBufferLength = 0;
2169         lock_ReleaseWrite(&scp->rw);
2170         cm_ReleaseSCache(scp);
2171         cm_ReleaseSCache(dscp);
2172         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2173                  scp, code, status);
2174         return;
2175     }
2176
2177     if (!bCheckOnly) {
2178         /* Drop all locks since the file is being deleted */
2179         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2180                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2181         if (code) {
2182             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2183             (*ResultCB)->ResultStatus = status;
2184             (*ResultCB)->ResultBufferLength = 0;
2185             lock_ReleaseWrite(&scp->rw);
2186             cm_ReleaseSCache(scp);
2187             cm_ReleaseSCache(dscp);
2188             osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp Lock failure scp=0x%p code=0x%x status=0x%x",
2189                      scp, code, status);
2190         }
2191
2192         /* the scp is now locked and current */
2193         key = cm_GenerateKey(CM_SESSION_IFS, ProcessId, 0);
2194
2195         code = cm_UnlockByKey(scp, key,
2196                               CM_UNLOCK_FLAG_BY_FID,
2197                               userp, &req);
2198
2199         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2200         lock_ReleaseWrite(&scp->rw);
2201
2202         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2203             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2204         else
2205             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2206     } else {
2207         lock_ReleaseWrite(&scp->rw);
2208     }
2209
2210     if (code == 0) {
2211         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
2212
2213         (*ResultCB)->ResultBufferLength = sizeof( AFSFileDeleteResultCB);
2214
2215         pResultCB = (AFSFileDeleteResultCB *)(*ResultCB)->ResultData;
2216
2217         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
2218         osi_Log0(afsd_logp, "RDR_DeleteFileEntry SUCCESS");
2219     } else {
2220         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2221         (*ResultCB)->ResultStatus = status;
2222         (*ResultCB)->ResultBufferLength = 0;
2223         osi_Log2(afsd_logp, "RDR_DeleteFileEntry FAILURE code=0x%x status=0x%x",
2224                   code, status);
2225     }
2226
2227     cm_ReleaseSCache(dscp);
2228     cm_ReleaseSCache(scp);
2229
2230     return;
2231 }
2232
2233 void
2234 RDR_RenameFileEntry( IN cm_user_t *userp,
2235                      IN WCHAR    *SourceFileNameCounted,
2236                      IN DWORD     SourceFileNameLength,
2237                      IN AFSFileID SourceFileId,
2238                      IN AFSFileRenameCB *pRenameCB,
2239                      IN BOOL bWow64,
2240                      IN DWORD ResultBufferLength,
2241                      IN OUT AFSCommResult **ResultCB)
2242 {
2243
2244     AFSFileRenameResultCB *pResultCB = NULL;
2245     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2246     AFSFileID              SourceParentId   = pRenameCB->SourceParentId;
2247     AFSFileID              TargetParentId   = pRenameCB->TargetParentId;
2248     WCHAR *                TargetFileNameCounted = pRenameCB->TargetName;
2249     DWORD                  TargetFileNameLength = pRenameCB->TargetNameLength;
2250     cm_fid_t               SourceParentFid;
2251     cm_fid_t               TargetParentFid;
2252     cm_fid_t               SourceFid;
2253     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2254     cm_fid_t               TargetFid;
2255     cm_scache_t *          oldDscp;
2256     cm_scache_t *          newDscp;
2257     cm_dirOp_t dirop;
2258     wchar_t                shortName[13];
2259     wchar_t                SourceFileName[260];
2260     wchar_t                TargetFileName[260];
2261     cm_dirFid_t            dfid;
2262     cm_req_t               req;
2263     afs_uint32             code;
2264     DWORD                  status;
2265
2266     RDR_InitReq(&req, bWow64);
2267
2268     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2269     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2270
2271     osi_Log4(afsd_logp, "RDR_RenameFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2272               SourceParentId.Cell,  SourceParentId.Volume,
2273               SourceParentId.Vnode, SourceParentId.Unique);
2274     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2275     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2276               TargetParentId.Cell,  TargetParentId.Volume,
2277               TargetParentId.Vnode, TargetParentId.Unique);
2278     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2279
2280     *ResultCB = (AFSCommResult *)malloc( size);
2281     if (!(*ResultCB))
2282         return;
2283
2284     memset( *ResultCB,
2285             '\0',
2286             size);
2287
2288     pResultCB = (AFSFileRenameResultCB *)(*ResultCB)->ResultData;
2289
2290     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2291     {
2292         osi_Log2(afsd_logp, "RDR_RenameFileEntry Invalid Name Length: src %u target %u",
2293                  SourceFileNameLength, TargetFileNameLength);
2294         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2295         return;
2296     }
2297
2298     SourceParentFid.cell   = SourceParentId.Cell;
2299     SourceParentFid.volume = SourceParentId.Volume;
2300     SourceParentFid.vnode  = SourceParentId.Vnode;
2301     SourceParentFid.unique = SourceParentId.Unique;
2302     SourceParentFid.hash   = SourceParentId.Hash;
2303
2304     TargetParentFid.cell   = TargetParentId.Cell;
2305     TargetParentFid.volume = TargetParentId.Volume;
2306     TargetParentFid.vnode  = TargetParentId.Vnode;
2307     TargetParentFid.unique = TargetParentId.Unique;
2308     TargetParentFid.hash   = TargetParentId.Hash;
2309
2310     code = cm_GetSCache(&SourceParentFid, NULL, &oldDscp, userp, &req);
2311     if (code) {
2312         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache source parent failed code 0x%x", code);
2313         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2314         if ( status == STATUS_INVALID_HANDLE)
2315             status = STATUS_OBJECT_PATH_INVALID;
2316         (*ResultCB)->ResultStatus = status;
2317         return;
2318     }
2319
2320     lock_ObtainWrite(&oldDscp->rw);
2321     code = cm_SyncOp(oldDscp, NULL, userp, &req, 0,
2322                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2323     if (code) {
2324         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp oldDscp 0x%p failed code 0x%x", oldDscp, code);
2325         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2326         if ( status == STATUS_INVALID_HANDLE)
2327             status = STATUS_OBJECT_PATH_INVALID;
2328         (*ResultCB)->ResultStatus = status;
2329         lock_ReleaseWrite(&oldDscp->rw);
2330         cm_ReleaseSCache(oldDscp);
2331         return;
2332     }
2333
2334     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2335     lock_ReleaseWrite(&oldDscp->rw);
2336
2337
2338     if (oldDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2339         osi_Log1(afsd_logp, "RDR_RenameFileEntry oldDscp 0x%p not a directory", oldDscp);
2340         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2341         cm_ReleaseSCache(oldDscp);
2342         return;
2343     }
2344
2345     code = cm_GetSCache(&TargetParentFid, NULL, &newDscp, userp, &req);
2346     if (code) {
2347         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target parent failed code 0x%x", code);
2348         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2349         (*ResultCB)->ResultStatus = status;
2350         cm_ReleaseSCache(oldDscp);
2351         return;
2352     }
2353
2354     lock_ObtainWrite(&newDscp->rw);
2355     code = cm_SyncOp(newDscp, NULL, userp, &req, 0,
2356                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2357     if (code) {
2358         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp newDscp 0x%p failed code 0x%x", newDscp, code);
2359         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2360         (*ResultCB)->ResultStatus = status;
2361         lock_ReleaseWrite(&newDscp->rw);
2362         cm_ReleaseSCache(oldDscp);
2363         cm_ReleaseSCache(newDscp);
2364         return;
2365     }
2366
2367     cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2368     lock_ReleaseWrite(&newDscp->rw);
2369
2370
2371     if (newDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2372         osi_Log1(afsd_logp, "RDR_RenameFileEntry newDscp 0x%p not a directory", newDscp);
2373         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2374         cm_ReleaseSCache(oldDscp);
2375         cm_ReleaseSCache(newDscp);
2376         return;
2377     }
2378
2379     /* Obtain the original FID just for debugging purposes */
2380     code = cm_BeginDirOp( oldDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2381     if (code == 0) {
2382         code = cm_BPlusDirLookup(&dirop, SourceFileName, &SourceFid);
2383         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2384         cm_EndDirOp(&dirop);
2385     }
2386
2387     code = cm_Rename( oldDscp, NULL, SourceFileName,
2388                       newDscp, TargetFileName, userp, &req);
2389     if (code == 0) {
2390         cm_scache_t *scp = 0;
2391         DWORD dwRemaining;
2392
2393         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2394         dwRemaining = ResultBufferLength - sizeof( AFSFileRenameResultCB) + sizeof( AFSDirEnumEntry);
2395         (*ResultCB)->ResultStatus = 0;
2396
2397         pResultCB->SourceParentDataVersion.QuadPart = oldDscp->dataVersion;
2398         pResultCB->TargetParentDataVersion.QuadPart = newDscp->dataVersion;
2399
2400         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p SUCCESS",
2401                  oldDscp, newDscp);
2402
2403         code = cm_BeginDirOp( newDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2404         if (code == 0) {
2405             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2406             cm_EndDirOp(&dirop);
2407         }
2408
2409         if (code != 0) {
2410             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_BPlusDirLookup failed code 0x%x",
2411                      code);
2412             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2413             cm_ReleaseSCache(oldDscp);
2414             cm_ReleaseSCache(newDscp);
2415             return;
2416         }
2417
2418         osi_Log4(afsd_logp, "RDR_RenameFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2419                   TargetFid.cell,  TargetFid.volume,
2420                   TargetFid.vnode, TargetFid.unique);
2421
2422         code = cm_GetSCache(&TargetFid, &newDscp->fid, &scp, userp, &req);
2423         if (code) {
2424             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target failed code 0x%x", code);
2425             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2426             (*ResultCB)->ResultStatus = status;
2427             cm_ReleaseSCache(oldDscp);
2428             cm_ReleaseSCache(newDscp);
2429             return;
2430         }
2431
2432         /* Make sure the source vnode is current */
2433         lock_ObtainWrite(&scp->rw);
2434         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2435                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2436         if (code) {
2437             osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp scp 0x%p failed code 0x%x", scp, code);
2438             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2439             (*ResultCB)->ResultStatus = status;
2440             lock_ReleaseWrite(&scp->rw);
2441             cm_ReleaseSCache(oldDscp);
2442             cm_ReleaseSCache(newDscp);
2443             cm_ReleaseSCache(scp);
2444             return;
2445         }
2446
2447         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2448         lock_ReleaseWrite(&scp->rw);
2449
2450         if (cm_shortNames) {
2451             dfid.vnode = htonl(scp->fid.vnode);
2452             dfid.unique = htonl(scp->fid.unique);
2453
2454             if (!cm_Is8Dot3(TargetFileName))
2455                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2456             else
2457                 shortName[0] = '\0';
2458         }
2459
2460         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2461                                  newDscp, scp, userp, &req, TargetFileName, shortName,
2462                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2463                                  0, NULL, &dwRemaining);
2464         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2465         cm_ReleaseSCache(scp);
2466
2467         osi_Log0(afsd_logp, "RDR_RenameFileEntry SUCCESS");
2468     } else {
2469         osi_Log3(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p failed code 0x%x",
2470                  oldDscp, newDscp, code);
2471         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2472         (*ResultCB)->ResultStatus = status;
2473         (*ResultCB)->ResultBufferLength = 0;
2474     }
2475
2476     cm_ReleaseSCache(oldDscp);
2477     cm_ReleaseSCache(newDscp);
2478     return;
2479 }
2480
2481 /*
2482  * AFS does not support cross-directory hard links but RDR_HardLinkFileEntry
2483  * is written as if AFS does.  The check for cross-directory links is
2484  * implemented in cm_Link().
2485  *
2486  * Windows supports optional ReplaceIfExists functionality.  The AFS file
2487  * server does not.  If the target name already exists and bReplaceIfExists
2488  * is true, check to see if the user has insert permission before calling
2489  * cm_Unlink() on the existing object.  If the user does not have insert
2490  * permission return STATUS_ACCESS_DENIED.
2491  */
2492
2493 void
2494 RDR_HardLinkFileEntry( IN cm_user_t *userp,
2495                        IN WCHAR    *SourceFileNameCounted,
2496                        IN DWORD     SourceFileNameLength,
2497                        IN AFSFileID SourceFileId,
2498                        IN AFSFileHardLinkCB *pHardLinkCB,
2499                        IN BOOL bWow64,
2500                        IN DWORD ResultBufferLength,
2501                        IN OUT AFSCommResult **ResultCB)
2502 {
2503
2504     AFSFileHardLinkResultCB *pResultCB = NULL;
2505     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2506     AFSFileID              SourceParentId   = pHardLinkCB->SourceParentId;
2507     AFSFileID              TargetParentId   = pHardLinkCB->TargetParentId;
2508     WCHAR *                TargetFileNameCounted = pHardLinkCB->TargetName;
2509     DWORD                  TargetFileNameLength = pHardLinkCB->TargetNameLength;
2510     cm_fid_t               SourceParentFid;
2511     cm_fid_t               TargetParentFid;
2512     cm_fid_t               SourceFid;
2513     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2514     cm_scache_t *          srcDscp = NULL;
2515     cm_scache_t *          targetDscp = NULL;
2516     cm_scache_t *          srcScp = NULL;
2517     cm_dirOp_t             dirop;
2518     wchar_t                shortName[13];
2519     wchar_t                SourceFileName[260];
2520     wchar_t                TargetFileName[260];
2521     cm_dirFid_t            dfid;
2522     cm_req_t               req;
2523     afs_uint32             code;
2524     DWORD                  status;
2525
2526     RDR_InitReq(&req, bWow64);
2527
2528     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2529     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2530
2531     osi_Log4(afsd_logp, "RDR_HardLinkFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2532               SourceParentId.Cell,  SourceParentId.Volume,
2533               SourceParentId.Vnode, SourceParentId.Unique);
2534     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2535     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2536               TargetParentId.Cell,  TargetParentId.Volume,
2537               TargetParentId.Vnode, TargetParentId.Unique);
2538     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2539
2540     *ResultCB = (AFSCommResult *)malloc( size);
2541     if (!(*ResultCB))
2542         return;
2543
2544     memset( *ResultCB,
2545             '\0',
2546             size);
2547
2548     pResultCB = (AFSFileHardLinkResultCB *)(*ResultCB)->ResultData;
2549
2550     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2551     {
2552         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry Invalid Name Length: src %u target %u",
2553                  SourceFileNameLength, TargetFileNameLength);
2554         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2555         return;
2556     }
2557
2558     SourceFid.cell   = SourceFileId.Cell;
2559     SourceFid.volume = SourceFileId.Volume;
2560     SourceFid.vnode  = SourceFileId.Vnode;
2561     SourceFid.unique = SourceFileId.Unique;
2562     SourceFid.hash   = SourceFileId.Hash;
2563
2564     SourceParentFid.cell   = SourceParentId.Cell;
2565     SourceParentFid.volume = SourceParentId.Volume;
2566     SourceParentFid.vnode  = SourceParentId.Vnode;
2567     SourceParentFid.unique = SourceParentId.Unique;
2568     SourceParentFid.hash   = SourceParentId.Hash;
2569
2570     TargetParentFid.cell   = TargetParentId.Cell;
2571     TargetParentFid.volume = TargetParentId.Volume;
2572     TargetParentFid.vnode  = TargetParentId.Vnode;
2573     TargetParentFid.unique = TargetParentId.Unique;
2574     TargetParentFid.hash   = TargetParentId.Hash;
2575
2576     code = cm_GetSCache(&SourceFid, NULL, &srcScp, userp, &req);
2577     if (code) {
2578         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache source failed code 0x%x", code);
2579         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2580         (*ResultCB)->ResultStatus = status;
2581         return;
2582     }
2583
2584     code = cm_GetSCache(&TargetParentFid, NULL, &targetDscp, userp, &req);
2585     if (code) {
2586         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache target parent failed code 0x%x", code);
2587         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2588         (*ResultCB)->ResultStatus = status;
2589         cm_ReleaseSCache(srcScp);
2590         return;
2591     }
2592
2593     lock_ObtainWrite(&targetDscp->rw);
2594     code = cm_SyncOp(targetDscp, NULL, userp, &req, PRSFS_INSERT,
2595                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2596     if (code) {
2597         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp targetDscp 0x%p failed code 0x%x", targetDscp, code);
2598         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2599         (*ResultCB)->ResultStatus = status;
2600         lock_ReleaseWrite(&targetDscp->rw);
2601         cm_ReleaseSCache(srcScp);
2602         cm_ReleaseSCache(targetDscp);
2603         return;
2604     }
2605
2606     cm_SyncOpDone(targetDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2607     lock_ReleaseWrite(&targetDscp->rw);
2608
2609     if (targetDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2610         osi_Log1(afsd_logp, "RDR_HardLinkFileEntry targetDscp 0x%p not a directory", targetDscp);
2611         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2612         cm_ReleaseSCache(srcScp);
2613         cm_ReleaseSCache(targetDscp);
2614         return;
2615     }
2616
2617     if ( cm_FidCmp(&SourceParentFid, &TargetParentFid) ) {
2618         code = cm_GetSCache(&SourceParentFid, NULL, &srcDscp, userp, &req);
2619         if (code) {
2620             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache source parent failed code 0x%x", 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             cm_ReleaseSCache(srcScp);
2626             cm_ReleaseSCache(targetDscp);
2627             return;
2628         }
2629
2630         lock_ObtainWrite(&srcDscp->rw);
2631         code = cm_SyncOp(srcDscp, NULL, userp, &req, 0,
2632                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2633         if (code) {
2634             osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp srcDscp 0x%p failed code 0x%x", srcDscp, code);
2635             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2636             if ( status == STATUS_INVALID_HANDLE)
2637                 status = STATUS_OBJECT_PATH_INVALID;
2638             (*ResultCB)->ResultStatus = status;
2639             lock_ReleaseWrite(&srcDscp->rw);
2640             if (srcDscp != targetDscp)
2641                 cm_ReleaseSCache(srcDscp);
2642             cm_ReleaseSCache(targetDscp);
2643             cm_ReleaseSCache(srcScp);
2644             return;
2645         }
2646
2647         cm_SyncOpDone(srcDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2648         lock_ReleaseWrite(&srcDscp->rw);
2649
2650         if (srcDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2651             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry srcDscp 0x%p not a directory", srcDscp);
2652             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2653             if (srcDscp != targetDscp)
2654                 cm_ReleaseSCache(srcDscp);
2655             cm_ReleaseSCache(targetDscp);
2656             cm_ReleaseSCache(srcScp);
2657             return;
2658         }
2659     } else {
2660         srcDscp = targetDscp;
2661     }
2662
2663     /* Obtain the target FID if it exists */
2664     code = cm_BeginDirOp( targetDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2665     if (code == 0) {
2666         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2667         cm_EndDirOp(&dirop);
2668     }
2669
2670     if (OrigTargetFid.vnode) {
2671
2672         /* An object exists with the target name */
2673         if (!pHardLinkCB->bReplaceIfExists) {
2674             osi_Log0(afsd_logp, "RDR_HardLinkFileEntry target name collision and !ReplaceIfExists");
2675             (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_COLLISION;
2676             if (srcDscp != targetDscp)
2677                 cm_ReleaseSCache(srcDscp);
2678             cm_ReleaseSCache(targetDscp);
2679             cm_ReleaseSCache(srcScp);
2680             return;
2681         }
2682
2683         lock_ObtainWrite(&targetDscp->rw);
2684         code = cm_SyncOp(targetDscp, NULL, userp, &req, PRSFS_INSERT | PRSFS_DELETE,
2685                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2686         if (code) {
2687             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2688             (*ResultCB)->ResultStatus = status;
2689             lock_ReleaseWrite(&srcDscp->rw);
2690             if (srcDscp != targetDscp)
2691                 cm_ReleaseSCache(srcDscp);
2692             cm_ReleaseSCache(targetDscp);
2693             cm_ReleaseSCache(srcScp);
2694             return;
2695         }
2696         cm_SyncOpDone(targetDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2697         lock_ReleaseWrite(&targetDscp->rw);
2698
2699         code = cm_Unlink(targetDscp, NULL, TargetFileName, userp, &req);
2700         if (code) {
2701             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_Unlink code 0x%x", code);
2702             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2703             (*ResultCB)->ResultStatus = status;
2704             lock_ReleaseWrite(&srcDscp->rw);
2705             if (srcDscp != targetDscp)
2706                 cm_ReleaseSCache(srcDscp);
2707             cm_ReleaseSCache(targetDscp);
2708             cm_ReleaseSCache(srcScp);
2709             return;
2710         }
2711     }
2712
2713     code = cm_Link( targetDscp, TargetFileName, srcScp, 0, userp, &req);
2714     if (code == 0) {
2715         cm_fid_t TargetFid;
2716         cm_scache_t *targetScp = 0;
2717         DWORD dwRemaining;
2718
2719         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2720         dwRemaining = ResultBufferLength - sizeof( AFSFileHardLinkResultCB) + sizeof( AFSDirEnumEntry);
2721         (*ResultCB)->ResultStatus = 0;
2722
2723         pResultCB->SourceParentDataVersion.QuadPart = srcDscp->dataVersion;
2724         pResultCB->TargetParentDataVersion.QuadPart = targetDscp->dataVersion;
2725
2726         osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_Link srcDscp 0x%p targetDscp 0x%p SUCCESS",
2727                  srcDscp, targetDscp);
2728
2729         code = cm_BeginDirOp( targetDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2730         if (code == 0) {
2731             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2732             cm_EndDirOp(&dirop);
2733         }
2734
2735         if (code != 0) {
2736             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_BPlusDirLookup failed code 0x%x",
2737                      code);
2738             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2739             if (srcDscp != targetDscp)
2740                 cm_ReleaseSCache(srcDscp);
2741             cm_ReleaseSCache(srcScp);
2742             cm_ReleaseSCache(targetDscp);
2743             return;
2744         }
2745
2746         osi_Log4(afsd_logp, "RDR_HardLinkFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2747                   TargetFid.cell,  TargetFid.volume,
2748                   TargetFid.vnode, TargetFid.unique);
2749
2750         code = cm_GetSCache(&TargetFid, &targetDscp->fid, &targetScp, userp, &req);
2751         if (code) {
2752             osi_Log1(afsd_logp, "RDR_HardLinkFileEntry cm_GetSCache target failed code 0x%x", code);
2753             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2754             (*ResultCB)->ResultStatus = status;
2755             if (srcDscp != targetDscp)
2756                 cm_ReleaseSCache(srcDscp);
2757             cm_ReleaseSCache(srcScp);
2758             cm_ReleaseSCache(targetDscp);
2759             return;
2760         }
2761
2762         /* Make sure the source vnode is current */
2763         lock_ObtainWrite(&targetScp->rw);
2764         code = cm_SyncOp(targetScp, NULL, userp, &req, 0,
2765                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2766         if (code) {
2767             osi_Log2(afsd_logp, "RDR_HardLinkFileEntry cm_SyncOp scp 0x%p failed code 0x%x",
2768                      targetScp, code);
2769             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2770             (*ResultCB)->ResultStatus = status;
2771             lock_ReleaseWrite(&targetScp->rw);
2772             cm_ReleaseSCache(targetScp);
2773             if (srcDscp != targetDscp)
2774                 cm_ReleaseSCache(srcDscp);
2775             cm_ReleaseSCache(srcScp);
2776             cm_ReleaseSCache(targetDscp);
2777             return;
2778         }
2779
2780         cm_SyncOpDone(targetScp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2781         lock_ReleaseWrite(&targetScp->rw);
2782
2783         if (cm_shortNames) {
2784             dfid.vnode = htonl(targetScp->fid.vnode);
2785             dfid.unique = htonl(targetScp->fid.unique);
2786
2787             if (!cm_Is8Dot3(TargetFileName))
2788                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2789             else
2790                 shortName[0] = '\0';
2791         }
2792
2793         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2794                                  targetDscp, targetScp, userp, &req, TargetFileName, shortName,
2795                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2796                                  0, NULL, &dwRemaining);
2797         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2798         cm_ReleaseSCache(targetScp);
2799
2800         osi_Log0(afsd_logp, "RDR_HardLinkFileEntry SUCCESS");
2801     } else {
2802         osi_Log3(afsd_logp, "RDR_HardLinkFileEntry cm_Link srcDscp 0x%p targetDscp 0x%p failed code 0x%x",
2803                  srcDscp, targetDscp, code);
2804         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2805         (*ResultCB)->ResultStatus = status;
2806         (*ResultCB)->ResultBufferLength = 0;
2807     }
2808
2809     cm_ReleaseSCache(srcScp);
2810     if (srcDscp != targetDscp)
2811         cm_ReleaseSCache(srcDscp);
2812     cm_ReleaseSCache(targetDscp);
2813     return;
2814 }
2815
2816 void
2817 RDR_FlushFileEntry( IN cm_user_t *userp,
2818                     IN AFSFileID FileId,
2819                     IN BOOL bWow64,
2820                     IN DWORD ResultBufferLength,
2821                     IN OUT AFSCommResult **ResultCB)
2822 {
2823     cm_scache_t *scp = NULL;
2824     cm_fid_t    Fid;
2825     afs_uint32  code;
2826     cm_req_t    req;
2827     DWORD       status;
2828 #ifdef ODS_DEBUG
2829     char        dbgstr[1024];
2830 #endif
2831
2832     RDR_InitReq(&req, bWow64);
2833
2834     osi_Log4(afsd_logp, "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x",
2835               FileId.Cell, FileId.Volume,
2836               FileId.Vnode, FileId.Unique);
2837 #ifdef ODS_DEBUG
2838     snprintf( dbgstr, 1024,
2839               "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x\n",
2840               FileId.Cell, FileId.Volume,
2841               FileId.Vnode, FileId.Unique);
2842     OutputDebugStringA( dbgstr);
2843 #endif
2844
2845     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2846     if (!(*ResultCB)) {
2847         osi_Log0(afsd_logp, "RDR_FlushFileEntry out of memory");
2848         return;
2849     }
2850
2851     memset( *ResultCB,
2852             '\0',
2853             sizeof( AFSCommResult));
2854
2855     /* Process the release */
2856     Fid.cell = FileId.Cell;
2857     Fid.volume = FileId.Volume;
2858     Fid.vnode = FileId.Vnode;
2859     Fid.unique = FileId.Unique;
2860     Fid.hash = FileId.Hash;
2861
2862     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2863     if (code) {
2864         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2865         (*ResultCB)->ResultStatus = status;
2866         osi_Log2(afsd_logp, "RDR_FlushFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2867                   code, status);
2868         return;
2869     }
2870
2871     lock_ObtainWrite(&scp->rw);
2872     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2873         lock_ReleaseWrite(&scp->rw);
2874         (*ResultCB)->ResultStatus = STATUS_INVALID_HANDLE;
2875         return;
2876     }
2877
2878     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2879                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2880     if (code) {
2881         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2882         (*ResultCB)->ResultStatus = status;
2883         lock_ReleaseWrite(&scp->rw);
2884         cm_ReleaseSCache(scp);
2885         osi_Log3(afsd_logp, "RDR_FlushFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2886                  scp, code, status);
2887         return;
2888     }
2889
2890     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2891     lock_ReleaseWrite(&scp->rw);
2892
2893     code = cm_FSync(scp, userp, &req, FALSE);
2894     cm_ReleaseSCache(scp);
2895
2896     if (code) {
2897         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2898         (*ResultCB)->ResultStatus = status;
2899         osi_Log2(afsd_logp, "RDR_FlushFileEntry FAILURE code=0x%x status=0x%x",
2900                   code, status);
2901     } else {
2902         (*ResultCB)->ResultStatus = 0;
2903         osi_Log0(afsd_logp, "RDR_FlushFileEntry SUCCESS");
2904     }
2905     (*ResultCB)->ResultBufferLength = 0;
2906
2907     return;
2908 }
2909
2910 afs_uint32
2911 RDR_CheckAccess( IN cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
2912                  ULONG access,
2913                  ULONG *granted)
2914 {
2915     ULONG afs_acc, afs_gr;
2916     BOOLEAN file, dir;
2917     afs_uint32 code = 0;
2918
2919     file = (scp->fileType == CM_SCACHETYPE_FILE);
2920     dir = !file;
2921
2922     /* access definitions from prs_fs.h */
2923     afs_acc = 0;
2924     if (access & FILE_READ_DATA)
2925         afs_acc |= PRSFS_READ;
2926     if (access & FILE_READ_EA || access & FILE_READ_ATTRIBUTES)
2927         afs_acc |= PRSFS_READ;
2928     if (file && ((access & FILE_WRITE_DATA) || (access & FILE_APPEND_DATA)))
2929         afs_acc |= PRSFS_WRITE;
2930     if (access & FILE_WRITE_EA || access & FILE_WRITE_ATTRIBUTES)
2931         afs_acc |= PRSFS_WRITE;
2932     if (dir && ((access & FILE_ADD_FILE) || (access & FILE_ADD_SUBDIRECTORY)))
2933         afs_acc |= PRSFS_INSERT;
2934     if (dir && (access & FILE_LIST_DIRECTORY))
2935         afs_acc |= PRSFS_LOOKUP;
2936     if (file && (access & FILE_EXECUTE))
2937         afs_acc |= PRSFS_WRITE;
2938     if (dir && (access & FILE_TRAVERSE))
2939         afs_acc |= PRSFS_READ;
2940     if (dir && (access & FILE_DELETE_CHILD))
2941         afs_acc |= PRSFS_DELETE;
2942     if ((access & DELETE))
2943         afs_acc |= PRSFS_DELETE;
2944
2945     /* check ACL with server */
2946     lock_ObtainWrite(&scp->rw);
2947     while (1)
2948     {
2949         if (cm_HaveAccessRights(scp, userp, reqp, afs_acc, &afs_gr))
2950         {
2951             break;
2952         }
2953         else
2954         {
2955             /* we don't know the required access rights */
2956             code = cm_GetAccessRights(scp, userp, reqp);
2957             if (code)
2958                 break;
2959             continue;
2960         }
2961     }
2962     lock_ReleaseWrite(&(scp->rw));
2963
2964     if (code == 0) {
2965         *granted = 0;
2966         if (afs_gr & PRSFS_READ)
2967             *granted |= FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_EXECUTE;
2968         if (afs_gr & PRSFS_WRITE)
2969             *granted |= FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_EXECUTE;
2970         if (afs_gr & PRSFS_INSERT)
2971             *granted |= (dir ? FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY : 0) | (file ? FILE_ADD_SUBDIRECTORY : 0);
2972         if (afs_gr & PRSFS_LOOKUP)
2973             *granted |= (dir ? FILE_LIST_DIRECTORY : 0);
2974         if (afs_gr & PRSFS_DELETE)
2975             *granted |= FILE_DELETE_CHILD | DELETE;
2976         if (afs_gr & PRSFS_LOCK)
2977             *granted |= 0;
2978         if (afs_gr & PRSFS_ADMINISTER)
2979             *granted |= 0;
2980
2981         *granted |= SYNCHRONIZE | READ_CONTROL;
2982
2983         /* don't give more access than what was requested */
2984         *granted &= access;
2985         osi_Log3(afsd_logp, "RDR_CheckAccess SUCCESS scp=0x%p requested=0x%x granted=0x%x", scp, access, *granted);
2986     } else
2987         osi_Log2(afsd_logp, "RDR_CheckAccess FAILURE scp=0x%p code=0x%x",
2988                  scp, code);
2989
2990     return code;
2991 }
2992
2993 void
2994 RDR_OpenFileEntry( IN cm_user_t *userp,
2995                    IN AFSFileID FileId,
2996                    IN AFSFileOpenCB *OpenCB,
2997                    IN BOOL bWow64,
2998                    IN BOOL bHoldFid,
2999                    IN DWORD ResultBufferLength,
3000                    IN OUT AFSCommResult **ResultCB)
3001 {
3002     AFSFileOpenResultCB *pResultCB = NULL;
3003     cm_scache_t *scp = NULL;
3004     cm_user_t   *sysUserp = NULL;
3005     cm_fid_t    Fid;
3006     cm_lock_data_t      *ldp = NULL;
3007     afs_uint32  code;
3008     cm_req_t    req;
3009     DWORD       status;
3010
3011     RDR_InitReq(&req, bWow64);
3012
3013     osi_Log4(afsd_logp, "RDR_OpenFileEntry File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3014               FileId.Cell, FileId.Volume,
3015               FileId.Vnode, FileId.Unique);
3016
3017     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
3018     if (!(*ResultCB)) {
3019         osi_Log0(afsd_logp, "RDR_OpenFileEntry out of memory");
3020         return;
3021     }
3022
3023     memset( *ResultCB,
3024             '\0',
3025             sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
3026
3027     pResultCB = (AFSFileOpenResultCB *)(*ResultCB)->ResultData;
3028
3029     /* Process the release */
3030     Fid.cell = FileId.Cell;
3031     Fid.volume = FileId.Volume;
3032     Fid.vnode = FileId.Vnode;
3033     Fid.unique = FileId.Unique;
3034     Fid.hash = FileId.Hash;
3035
3036     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3037     if (code) {
3038         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3039         (*ResultCB)->ResultStatus = status;
3040         osi_Log2(afsd_logp, "RDR_OpenFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
3041                   code, status);
3042         return;
3043     }
3044
3045     lock_ObtainWrite(&scp->rw);
3046     code = cm_SyncOp(scp, NULL, userp, &req, 0,
3047                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3048     if (code) {
3049         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3050         (*ResultCB)->ResultStatus = status;
3051         lock_ReleaseWrite(&scp->rw);
3052         cm_ReleaseSCache(scp);
3053         osi_Log3(afsd_logp, "RDR_OpenFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
3054                  scp, code, status);
3055         return;
3056     }
3057
3058     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3059     lock_ReleaseWrite(&scp->rw);
3060
3061     sysUserp = RDR_GetLocalSystemUser();
3062
3063     /*
3064      * Skip the open check if the request is coming from the local system account.
3065      * The local system has no tokens and therefore any requests sent to a file
3066      * server will fail.  Unfortunately, there are special system processes that
3067      * perform actions on files and directories in preparation for memory mapping
3068      * executables.  If the open check fails, the real request from the user process
3069      * will never be issued.
3070      *
3071      * Permitting the file system to allow subsequent operations to proceed does
3072      * not compromise security.  All requests to obtain file data or directory
3073      * enumerations will subsequently fail if they are not submitted under the
3074      * context of a process for that have access to the necessary credentials.
3075      */
3076
3077     if ( userp == sysUserp)
3078     {
3079         osi_Log1(afsd_logp, "RDR_OpenFileEntry LOCAL_SYSTEM access check skipped scp=0x%p",
3080                  scp);
3081         pResultCB->GrantedAccess = OpenCB->DesiredAccess;
3082         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3083         code = 0;
3084     }
3085     else
3086     {
3087         int count = 0;
3088
3089         pResultCB->Authenticated = cm_HaveToken(userp, scp->fid.cell);
3090
3091         do {
3092             if (count++ > 0) {
3093                 Sleep(350);
3094                 osi_Log3(afsd_logp,
3095                          "RDR_OpenFileEntry repeating open check scp=0x%p userp=0x%p code=0x%x",
3096                          scp, userp, code);
3097             }
3098             code = cm_CheckNTOpen(scp, OpenCB->DesiredAccess, OpenCB->ShareAccess,
3099                                   OPEN_ALWAYS,
3100                                   OpenCB->ProcessId, OpenCB->Identifier,
3101                                   userp, &req, &ldp);
3102             if (code == 0)
3103                 code = RDR_CheckAccess(scp, userp, &req, OpenCB->DesiredAccess, &pResultCB->GrantedAccess);
3104
3105
3106             cm_CheckNTOpenDone(scp, userp, &req, &ldp);
3107         } while (count < 100 && (code == CM_ERROR_RETRY || code == CM_ERROR_WOULDBLOCK));
3108     }
3109
3110     /*
3111      * If we are restricting sharing, we should do so with a suitable
3112      * share lock.
3113      */
3114     if (code == 0 && scp->fileType == CM_SCACHETYPE_FILE && !(OpenCB->ShareAccess & FILE_SHARE_WRITE)) {
3115         cm_key_t key;
3116         LARGE_INTEGER LOffset, LLength;
3117         int sLockType;
3118
3119         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
3120         LOffset.LowPart = SMB_FID_QLOCK_LOW;
3121         LLength.HighPart = 0;
3122         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
3123
3124         /*
3125          * If we are not opening the file for writing, then we don't
3126          * try to get an exclusive lock.  No one else should be able to
3127          * get an exclusive lock on the file anyway, although someone
3128          * else can get a shared lock.
3129          */
3130         if ((OpenCB->ShareAccess & FILE_SHARE_READ) || !(OpenCB->DesiredAccess & AFS_ACCESS_WRITE))
3131         {
3132             sLockType = LOCKING_ANDX_SHARED_LOCK;
3133         } else {
3134             sLockType = 0;
3135         }
3136
3137         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, OpenCB->Identifier);
3138
3139         lock_ObtainWrite(&scp->rw);
3140         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, &req, NULL);
3141         lock_ReleaseWrite(&scp->rw);
3142
3143         if (code) {
3144             code = CM_ERROR_SHARING_VIOLATION;
3145             pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3146         } else {
3147             if (sLockType == LOCKING_ANDX_SHARED_LOCK)
3148                 pResultCB->FileAccess = AFS_FILE_ACCESS_SHARED;
3149             else
3150                 pResultCB->FileAccess = AFS_FILE_ACCESS_EXCLUSIVE;
3151         }
3152     } else {
3153         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
3154     }
3155
3156     cm_ReleaseUser(sysUserp);
3157     if (code == 0 && bHoldFid)
3158         RDR_FlagScpInUse( scp, FALSE );
3159     cm_ReleaseSCache(scp);
3160
3161     if (code) {
3162         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3163         (*ResultCB)->ResultStatus = status;
3164         osi_Log2(afsd_logp, "RDR_OpenFileEntry FAILURE code=0x%x status=0x%x",
3165                   code, status);
3166     } else {
3167         (*ResultCB)->ResultStatus = 0;
3168         (*ResultCB)->ResultBufferLength = sizeof( AFSFileOpenResultCB);
3169         osi_Log0(afsd_logp, "RDR_OpenFileEntry SUCCESS");
3170     }
3171     return;
3172 }
3173
3174 void
3175 RDR_ReleaseFileAccess( IN cm_user_t *userp,
3176                        IN AFSFileID FileId,
3177                        IN AFSFileAccessReleaseCB *ReleaseFileCB,
3178                        IN BOOL bWow64,
3179                        IN DWORD ResultBufferLength,
3180                        IN OUT AFSCommResult **ResultCB)
3181 {
3182     cm_key_t key;
3183     unsigned int sLockType;
3184     LARGE_INTEGER LOffset, LLength;
3185     cm_scache_t *scp = NULL;
3186     cm_fid_t    Fid;
3187     afs_uint32  code;
3188     cm_req_t    req;
3189     DWORD       status;
3190
3191     RDR_InitReq(&req, bWow64);
3192
3193     osi_Log4(afsd_logp, "RDR_ReleaseFileAccess File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3194               FileId.Cell, FileId.Volume,
3195               FileId.Vnode, FileId.Unique);
3196
3197     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
3198     if (!(*ResultCB)) {
3199         osi_Log0(afsd_logp, "RDR_ReleaseFileAccess out of memory");
3200         return;
3201     }
3202
3203     memset( *ResultCB, '\0', sizeof( AFSCommResult));
3204
3205     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_NOLOCK)
3206         return;
3207
3208     /* Process the release */
3209     Fid.cell = FileId.Cell;
3210     Fid.volume = FileId.Volume;
3211     Fid.vnode = FileId.Vnode;
3212     Fid.unique = FileId.Unique;
3213     Fid.hash = FileId.Hash;
3214
3215     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3216     if (code) {
3217         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3218         (*ResultCB)->ResultStatus = status;
3219         osi_Log2(afsd_logp, "RDR_ReleaseFileAccess cm_GetSCache FID failure code=0x%x status=0x%x",
3220                   code, status);
3221         return;
3222     }
3223
3224     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_SHARED)
3225         sLockType = LOCKING_ANDX_SHARED_LOCK;
3226     else
3227         sLockType = 0;
3228
3229     key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, ReleaseFileCB->Identifier);
3230
3231     LOffset.HighPart = SMB_FID_QLOCK_HIGH;
3232     LOffset.LowPart = SMB_FID_QLOCK_LOW;
3233     LLength.HighPart = 0;
3234     LLength.LowPart = SMB_FID_QLOCK_LENGTH;
3235
3236     lock_ObtainWrite(&scp->rw);
3237
3238     code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
3239     if (code == 0)
3240     {
3241         code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
3242
3243         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
3244
3245         if (code == CM_ERROR_RANGE_NOT_LOCKED)
3246         {
3247             osi_Log3(afsd_logp, "RDR_ReleaseFileAccess Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
3248                      ReleaseFileCB->FileAccess, ReleaseFileCB->ProcessId, ReleaseFileCB->Identifier);
3249         }
3250     }
3251
3252     lock_ReleaseWrite(&scp->rw);
3253
3254     osi_Log0(afsd_logp, "RDR_ReleaseFileAccessEntry SUCCESS");
3255 }
3256
3257 static const char *
3258 HexCheckSum(unsigned char * buf, int buflen, unsigned char * md5cksum)
3259 {
3260     int i, k;
3261     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
3262
3263     if (buflen < 33)
3264         return "buffer length too small to HexCheckSum";
3265
3266     for (i=0;i<16;i++) {
3267         k = md5cksum[i];
3268
3269         buf[i*2] = tr[k / 16];
3270         buf[i*2+1] = tr[k % 16];
3271     }
3272     buf[32] = '\0';
3273
3274     return buf;
3275 }
3276
3277 /*
3278  * Extent requests from the file system are triggered when a file
3279  * page is not resident in the Windows cache.  The file system is
3280  * responsible for loading the page but cannot block the request
3281  * while doing so.  The AFS Redirector forwards the requests to
3282  * the AFS cache manager while indicating to Windows that the page
3283  * is not yet available.  A polling operation will then ensue with
3284  * the AFS Redirector issuing a RDR_RequestFileExtentsXXX call for
3285  * each poll attempt.  As each request is received and processed
3286  * by a separate worker thread in the service, this can lead to
3287  * contention by multiple threads attempting to claim the same
3288  * cm_buf_t objects.  Therefore, it is important that
3289  *
3290  *  (a) the service avoid processing more than one overlapping
3291  *      extent request at a time
3292  *  (b) background daemon processing be used to avoid blocking
3293  *      of ioctl threads
3294  *
3295  * Beginning with the 20091122 build of the redirector, the redirector
3296  * will not issue an additional RDR_RequestFileExtentsXXX call for
3297  * each poll request.  Instead, afsd_service is required to track
3298  * the requests and return them to the redirector or fail the
3299  * portions of the request that cannot be satisfied.
3300  *
3301  * The request processing returns any extents that can be returned
3302  * immediately to the redirector.  The rest of the requested range(s)
3303  * are queued as background operations using RDR_BkgFetch().
3304  */
3305
3306 /* do the background fetch. */
3307 afs_int32
3308 RDR_BkgFetch(cm_scache_t *scp, void *rockp, cm_user_t *userp, cm_req_t *reqp)
3309 {
3310     osi_hyper_t length;
3311     osi_hyper_t base;
3312     osi_hyper_t offset;
3313     osi_hyper_t end;
3314     osi_hyper_t fetched;
3315     osi_hyper_t tblocksize;
3316     afs_int32 code;
3317     int rwheld = 0;
3318     cm_buf_t *bufp = NULL;
3319     DWORD dwResultBufferLength;
3320     AFSSetFileExtentsCB *pResultCB;
3321     DWORD status;
3322     afs_uint32 count=0;
3323     AFSFileID FileId;
3324     int reportErrorToRedir = 0;
3325     int force_retry = 0;
3326
3327     FileId.Cell = scp->fid.cell;
3328     FileId.Volume = scp->fid.volume;
3329     FileId.Vnode = scp->fid.vnode;
3330     FileId.Unique = scp->fid.unique;
3331     FileId.Hash = scp->fid.hash;
3332
3333     fetched.LowPart = 0;
3334     fetched.HighPart = 0;
3335     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
3336     base = ((rock_BkgFetch_t *)rockp)->base;
3337     length = ((rock_BkgFetch_t *)rockp)->length;
3338     end = LargeIntegerAdd(base, length);
3339
3340     osi_Log5(afsd_logp, "Starting BKG Fetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
3341              scp, base.HighPart, base.LowPart, length.HighPart, length.LowPart);
3342
3343     /*
3344      * Make sure we have a callback.
3345      * This is necessary so that we can return access denied
3346      * if a callback cannot be granted.
3347      */
3348     lock_ObtainWrite(&scp->rw);
3349     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_READ,
3350                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3351     if (code) {
3352         lock_ReleaseWrite(&scp->rw);
3353         osi_Log2(afsd_logp, "RDR_BkgFetch cm_SyncOp failure scp=0x%p code=0x%x",
3354                  scp, code);
3355         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
3356         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3357         return code;
3358     }
3359     lock_ReleaseWrite(&scp->rw);
3360
3361     dwResultBufferLength = (DWORD)(sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (length.QuadPart / cm_data.blockSize + 1));
3362     pResultCB = (AFSSetFileExtentsCB *)malloc( dwResultBufferLength );
3363     if (!pResultCB)
3364         return CM_ERROR_RETRY;
3365
3366     memset( pResultCB, '\0', dwResultBufferLength );
3367     pResultCB->FileId = FileId;
3368
3369     for ( code = 0, offset = base;
3370           code == 0 && LargeIntegerLessThan(offset, end);
3371           offset = LargeIntegerAdd(offset, tblocksize) )
3372     {
3373         int bBufRelease = TRUE;
3374
3375         if (rwheld) {
3376             lock_ReleaseWrite(&scp->rw);
3377             rwheld = 0;
3378         }
3379
3380         code = buf_Get(scp, &offset, reqp, &bufp);
3381         if (code) {
3382             /*
3383              * any error from buf_Get() is non-fatal.
3384              * we need to re-queue this extent fetch.
3385              */
3386             force_retry = 1;
3387             break;
3388         }
3389
3390         if (!rwheld) {
3391             lock_ObtainWrite(&scp->rw);
3392             rwheld = 1;
3393         }
3394
3395         code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
3396         if (code == 0) {
3397             if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3398 #ifdef VALIDATE_CHECK_SUM
3399 #ifdef ODS_DEBUG
3400                 char md5dbg[33];
3401                 char dbgstr[1024];
3402 #endif
3403 #endif
3404                 if (bufp->flags & CM_BUF_DIRTY)
3405                     cm_BufWrite(scp, &bufp->offset, cm_data.buf_blockSize, CM_BUF_WRITE_SCP_LOCKED, userp, reqp);
3406
3407                 lock_ObtainWrite(&buf_globalLock);
3408                 if (!(bufp->flags & CM_BUF_DIRTY) &&
3409                     bufp->cmFlags == 0 &&
3410                     !(bufp->qFlags & CM_BUF_QREDIR)) {
3411                     buf_InsertToRedirQueue(scp, bufp);
3412                     lock_ReleaseWrite(&buf_globalLock);
3413
3414 #ifdef VALIDATE_CHECK_SUM
3415                     buf_ComputeCheckSum(bufp);
3416 #endif
3417                     pResultCB->FileExtents[count].Flags = 0;
3418                     pResultCB->FileExtents[count].FileOffset.QuadPart = bufp->offset.QuadPart;
3419                     pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3420                     pResultCB->FileExtents[count].Length = cm_data.blockSize;
3421                     count++;
3422                     fetched = LargeIntegerAdd(fetched, tblocksize);
3423                     bBufRelease = FALSE;
3424
3425 #ifdef VALIDATE_CHECK_SUM
3426 #ifdef ODS_DEBUG
3427                     HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3428                     snprintf( dbgstr, 1024,
3429                               "RDR_BkgFetch md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3430                               md5dbg,
3431                               scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3432                               pResultCB->FileExtents[count].FileOffset.HighPart,
3433                               pResultCB->FileExtents[count].FileOffset.LowPart,
3434                               pResultCB->FileExtents[count].CacheOffset.HighPart,
3435                               pResultCB->FileExtents[count].CacheOffset.LowPart);
3436                     OutputDebugStringA( dbgstr);
3437 #endif
3438 #endif
3439                     osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3440                               bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3441                 } else {
3442                     lock_ReleaseWrite(&buf_globalLock);
3443                     if ((bufp->cmFlags != 0) || (bufp->flags & CM_BUF_DIRTY)) {
3444                         /* An I/O operation is already in progress */
3445                         force_retry = 1;
3446                         osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Not delivering to Redirector Dirty or Busy bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3447                                   bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3448                     } else {
3449                         osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3450                                   bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3451                     }
3452                 }
3453             } else {
3454                 osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3455                           bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3456             }
3457         } else {
3458             /*
3459              * depending on what the error from cm_GetBuffer is
3460              * it may or may not be fatal.  Only return fatal errors.
3461              * Re-queue a request for others.
3462              */
3463             osi_Log5(afsd_logp, "RDR_BkgFetch Extent2FS FAILURE bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x code 0x%x",
3464                       bufp, offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize, code);
3465             switch (code) {
3466             case CM_ERROR_NOACCESS:
3467             case CM_ERROR_NOSUCHFILE:
3468             case CM_ERROR_NOSUCHPATH:
3469             case CM_ERROR_NOSUCHVOLUME:
3470             case CM_ERROR_NOSUCHCELL:
3471             case CM_ERROR_INVAL:
3472             case CM_ERROR_BADFD:
3473             case CM_ERROR_CLOCKSKEW:
3474             case RXKADNOAUTH:
3475             case CM_ERROR_QUOTA:
3476             case CM_ERROR_LOCK_CONFLICT:
3477             case EIO:
3478             case CM_ERROR_INVAL_NET_RESP:
3479             case CM_ERROR_UNKNOWN:
3480                 /*
3481                  * these are fatal errors.  deliver what we can
3482                  * and halt.
3483                  */
3484                 reportErrorToRedir = 1;
3485                 break;
3486             default:
3487                 /*
3488                  * non-fatal errors.  re-queue the exent
3489                  */
3490                 code = CM_ERROR_RETRY;
3491                 force_retry = 1;
3492             }
3493         }
3494
3495         if (bBufRelease)
3496             buf_Release(bufp);
3497     }
3498
3499     if (!rwheld) {
3500         lock_ObtainWrite(&scp->rw);
3501         rwheld = 1;
3502     }
3503
3504     /* wakeup anyone who is waiting */
3505     if (scp->flags & CM_SCACHEFLAG_WAITING) {
3506         osi_Log1(afsd_logp, "RDR Bkg Fetch Waking scp 0x%p", scp);
3507         osi_Wakeup((LONG_PTR) &scp->flags);
3508     }
3509     lock_ReleaseWrite(&scp->rw);
3510
3511     if (count > 0) {
3512         pResultCB->ExtentCount = count;
3513         RDR_SetFileExtents( pResultCB, dwResultBufferLength);
3514     }
3515     free(pResultCB);
3516
3517     if (reportErrorToRedir) {
3518         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
3519         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3520     }
3521
3522     osi_Log4(afsd_logp, "Ending BKG Fetch scp 0x%p code 0x%x fetched 0x%x:%x",
3523              scp, code, fetched.HighPart, fetched.LowPart);
3524
3525     return force_retry ? CM_ERROR_RETRY : code;
3526 }
3527
3528
3529 BOOL
3530 RDR_RequestFileExtentsAsync( IN cm_user_t *userp,
3531                              IN AFSFileID FileId,
3532                              IN AFSRequestExtentsCB *RequestExtentsCB,
3533                              IN BOOL bWow64,
3534                              IN OUT DWORD * ResultBufferLength,
3535                              IN OUT AFSSetFileExtentsCB **ResultCB)
3536 {
3537     AFSSetFileExtentsCB *pResultCB = NULL;
3538     DWORD Length;
3539     DWORD count;
3540     DWORD status;
3541     cm_scache_t *scp = NULL;
3542     cm_fid_t    Fid;
3543     cm_buf_t    *bufp;
3544     afs_uint32  code = 0;
3545     osi_hyper_t thyper;
3546     LARGE_INTEGER ByteOffset, BeginOffset, EndOffset, QueueOffset;
3547     afs_uint32  QueueLength;
3548     cm_req_t    req;
3549     BOOLEAN     bBufRelease = TRUE;
3550
3551     RDR_InitReq(&req, bWow64);
3552     req.flags |= CM_REQ_NORETRY;
3553
3554     osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3555               FileId.Cell, FileId.Volume,
3556               FileId.Vnode, FileId.Unique);
3557     osi_Log4(afsd_logp, "... Flags 0x%x ByteOffset 0x%x:%x Length 0x%x",
3558              RequestExtentsCB->Flags,
3559              RequestExtentsCB->ByteOffset.HighPart, RequestExtentsCB->ByteOffset.LowPart,
3560              RequestExtentsCB->Length);
3561     Length = sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (RequestExtentsCB->Length / cm_data.blockSize + 1);
3562
3563     pResultCB = *ResultCB = (AFSSetFileExtentsCB *)malloc( Length );
3564     if (*ResultCB == NULL) {
3565         *ResultBufferLength = 0;
3566         return FALSE;
3567     }
3568     *ResultBufferLength = Length;
3569
3570     memset( pResultCB, '\0', Length );
3571     pResultCB->FileId = FileId;
3572
3573     Fid.cell = FileId.Cell;
3574     Fid.volume = FileId.Volume;
3575     Fid.vnode = FileId.Vnode;
3576     Fid.unique = FileId.Unique;
3577     Fid.hash = FileId.Hash;
3578
3579     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3580     if (code) {
3581         osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync cm_GetSCache FID failure code=0x%x",
3582                   code);
3583         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3584         return FALSE;
3585     }
3586
3587     /*
3588      * Make sure we have a callback.
3589      * This is necessary so that we can return access denied
3590      * if a callback cannot be granted.
3591      */
3592     lock_ObtainWrite(&scp->rw);
3593     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
3594                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3595     lock_ReleaseWrite(&scp->rw);
3596     if (code) {
3597         cm_ReleaseSCache(scp);
3598         osi_Log2(afsd_logp, "RDR_RequestFileExtentsAsync cm_SyncOp failure scp=0x%p code=0x%x",
3599                  scp, code);
3600         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3601         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3602         return FALSE;
3603     }
3604
3605     /* Allocate the extents from the buffer package */
3606     for ( count = 0,
3607           ByteOffset = BeginOffset = RequestExtentsCB->ByteOffset,
3608           EndOffset.QuadPart = ByteOffset.QuadPart + RequestExtentsCB->Length;
3609           code == 0 && ByteOffset.QuadPart < EndOffset.QuadPart;
3610           ByteOffset.QuadPart += cm_data.blockSize)
3611     {
3612         BOOL bHaveBuffer = FALSE;
3613
3614         QueueLength = 0;
3615         thyper.QuadPart = ByteOffset.QuadPart;
3616
3617         code = buf_Get(scp, &thyper, &req, &bufp);
3618         if (code == 0) {
3619             lock_ObtainMutex(&bufp->mx);
3620             bBufRelease = TRUE;
3621
3622             if (bufp->qFlags & CM_BUF_QREDIR) {
3623                 bHaveBuffer = TRUE;
3624             } else if (bufp->flags & CM_BUF_DIRTY) {
3625                 bHaveBuffer = FALSE;
3626 #if 0
3627                 code = buf_CleanAsyncLocked(scp, bufp, &req, 0, NULL);
3628                 switch (code) {
3629                 case 0:
3630                     bHaveBuffer = TRUE;
3631                     break;
3632                 case CM_ERROR_RETRY:
3633                     /* Couldn't flush it, obtain it asynchronously so we don't block the thread. */
3634                     bHaveBuffer = FALSE;
3635                     code = 0;
3636                     break;
3637                 default:
3638                     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3639                     RDR_SetFileStatus(&FileId, &userp->authgroup, status);
3640                     bHaveBuffer = FALSE;
3641                     code = 0;
3642                 }
3643 #endif
3644             } else {
3645                 osi_hyper_t minLength;  /* effective end of file */
3646
3647                 lock_ObtainRead(&scp->rw);
3648                 bHaveBuffer = cm_HaveBuffer(scp, bufp, TRUE);
3649
3650                 if (LargeIntegerGreaterThan(scp->length, scp->serverLength))
3651                     minLength = scp->serverLength;
3652                 else
3653                     minLength = scp->length;
3654
3655                 if (LargeIntegerGreaterThanOrEqualTo(bufp->offset, minLength)) {
3656                     if (!bHaveBuffer) {
3657                         memset(bufp->datap, 0, cm_data.buf_blockSize);
3658                         bufp->dataVersion = scp->dataVersion;
3659                         bHaveBuffer = TRUE;
3660                     }
3661                     else if (bufp->dataVersion == CM_BUF_VERSION_BAD) {
3662                         bufp->dataVersion = scp->dataVersion;
3663                     }
3664                 }
3665                 else if ((RequestExtentsCB->Flags & AFS_EXTENT_FLAG_CLEAN) &&
3666                          ByteOffset.QuadPart <= bufp->offset.QuadPart &&
3667                          EndOffset.QuadPart >= bufp->offset.QuadPart + cm_data.blockSize)
3668                 {
3669                     memset(bufp->datap, 0, cm_data.blockSize);
3670                     bufp->dataVersion = scp->dataVersion;
3671                     buf_SetDirty(bufp, &req, 0, cm_data.blockSize, userp);
3672                     bHaveBuffer = TRUE;
3673                 }
3674                 lock_ReleaseRead(&scp->rw);
3675             }
3676
3677             /*
3678              * if this buffer is already up to date, skip it.
3679              */
3680             if (bHaveBuffer) {
3681                 if (ByteOffset.QuadPart == BeginOffset.QuadPart) {
3682                     BeginOffset.QuadPart += cm_data.blockSize;
3683                 } else {
3684                     QueueLength = (afs_uint32)(ByteOffset.QuadPart - BeginOffset.QuadPart);
3685                     QueueOffset = BeginOffset;
3686                     BeginOffset = ByteOffset;
3687                 }
3688
3689                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3690 #ifdef VALIDATE_CHECK_SUM
3691 #ifdef ODS_DEBUG
3692                     char md5dbg[33];
3693                     char dbgstr[1024];
3694 #endif
3695 #endif
3696                     lock_ObtainWrite(&buf_globalLock);
3697                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3698                         buf_InsertToRedirQueue(scp, bufp);
3699                         lock_ReleaseWrite(&buf_globalLock);
3700
3701 #ifdef VALIDATE_CHECK_SUM
3702                         buf_ComputeCheckSum(bufp);
3703 #endif
3704                         /* we already have the buffer, return it now */
3705                         pResultCB->FileExtents[count].Flags = 0;
3706                         pResultCB->FileExtents[count].FileOffset = ByteOffset;
3707                         pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3708                         pResultCB->FileExtents[count].Length = cm_data.blockSize;
3709                         count++;
3710
3711                         bBufRelease = FALSE;
3712
3713 #ifdef VALIDATE_CHECK_SUM
3714 #ifdef ODS_DEBUG
3715                         HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3716                         snprintf( dbgstr, 1024,
3717                                   "RDR_RequestFileExtentsAsync md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3718                                   md5dbg,
3719                                   scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3720                                   pResultCB->FileExtents[count].FileOffset.HighPart,
3721                                   pResultCB->FileExtents[count].FileOffset.LowPart,
3722                                   pResultCB->FileExtents[count].CacheOffset.HighPart,
3723                                   pResultCB->FileExtents[count].CacheOffset.LowPart);
3724                         OutputDebugStringA( dbgstr);
3725 #endif
3726 #endif
3727                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3728                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3729                     } else {
3730                         lock_ReleaseWrite(&buf_globalLock);
3731                     }
3732                 } else {
3733                     if (bBufRelease) {
3734                         /*
3735                          * The service is not handing off the extent to the redirector in this pass.
3736                          * However, we know the buffer is in recent use so move the buffer to the
3737                          * front of the queue
3738                          */
3739                         lock_ObtainWrite(&buf_globalLock);
3740                         buf_MoveToHeadOfRedirQueue(scp, bufp);
3741                         lock_ReleaseWrite(&buf_globalLock);
3742
3743                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3744                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3745                     }
3746                 }
3747             }
3748             lock_ReleaseMutex(&bufp->mx);
3749             if (bBufRelease)
3750                 buf_Release(bufp);
3751
3752             if (QueueLength) {
3753                 rock_BkgFetch_t * rockp = malloc(sizeof(*rockp));
3754
3755                 if (rockp) {
3756                     req.flags &= ~CM_REQ_NORETRY;
3757                     rockp->base = QueueOffset;
3758                     rockp->length.LowPart = QueueLength;
3759                     rockp->length.HighPart = 0;
3760
3761                     cm_QueueBKGRequest(scp, RDR_BkgFetch, rockp, userp, &req);
3762                     osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync Queued a Background Fetch offset 0x%x:%x length 0x%x",
3763                               QueueOffset.HighPart, QueueOffset.LowPart, QueueLength);
3764                     req.flags |= CM_REQ_NORETRY;
3765                 } else {
3766                     code = ENOMEM;
3767                 }
3768             }
3769         } else {
3770             /* No error from buf_Get() can be fatal */
3771             osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync buf_Get FAILURE offset 0x%x:%x code 0x%x",
3772                      BeginOffset.HighPart, BeginOffset.LowPart, code);
3773         }
3774     }
3775
3776     if (BeginOffset.QuadPart != EndOffset.QuadPart) {
3777         afs_uint32 length = (afs_uint32)(EndOffset.QuadPart - BeginOffset.QuadPart);
3778         rock_BkgFetch_t * rockp = malloc(sizeof(*rockp));
3779
3780         if (rockp) {
3781             req.flags &= ~CM_REQ_NORETRY;
3782             rockp->base = BeginOffset;
3783             rockp->length.LowPart = length;
3784             rockp->length.HighPart = 0;
3785
3786             cm_QueueBKGRequest(scp, RDR_BkgFetch, rockp, userp, &req);
3787             osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync Queued a Background Fetch offset 0x%x:%x length 0x%x",
3788                      BeginOffset.HighPart, BeginOffset.LowPart, length);
3789         } else {
3790             code = ENOMEM;
3791         }
3792     }
3793     cm_ReleaseSCache(scp);
3794
3795     (*ResultCB)->ExtentCount = count;
3796     osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync replying with 0x%x extent records", count);
3797     return FALSE;
3798 }
3799
3800 /*
3801  * When processing an extent release the extents must be accepted back by
3802  * the service even if there is an error condition returned to the redirector.
3803  * For example, there may no longer be a callback present or the file may
3804  * have been deleted on the file server.  Regardless, the extents must be
3805  * put back into the pool.
3806  */
3807 void
3808 RDR_ReleaseFileExtents( IN cm_user_t *userp,
3809                         IN AFSFileID FileId,
3810                         IN AFSReleaseExtentsCB *ReleaseExtentsCB,
3811                         IN BOOL bWow64,
3812                         IN DWORD ResultBufferLength,
3813                         IN OUT AFSCommResult **ResultCB)
3814 {
3815     DWORD count;
3816     cm_scache_t *scp = NULL;
3817     cm_fid_t    Fid;
3818     cm_buf_t    *bufp;
3819     afs_uint32  code;
3820     osi_hyper_t thyper;
3821     cm_req_t    req;
3822     int         dirty = 0;
3823     int         released = 0;
3824     int         deleted = 0;
3825     DWORD       status;
3826     rock_BkgStore_t *rockp;
3827 #ifdef ODS_DEBUG
3828 #ifdef VALIDATE_CHECK_SUM
3829     char md5dbg[33], md5dbg2[33], md5dbg3[33];
3830 #endif
3831     char dbgstr[1024];
3832 #endif
3833
3834     RDR_InitReq(&req, bWow64);
3835
3836     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3837               FileId.Cell, FileId.Volume,
3838               FileId.Vnode, FileId.Unique);
3839
3840     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
3841     if (!(*ResultCB))
3842         return;
3843