0c12007096cce72a5575ea41e733ca713d39989a
[openafs.git] / src / WINNT / afsrdr / user / RDRFunction.c
1 /*
2  * Copyright (c) 2008 Secure Endpoints, Inc.
3  * Copyright (c) 2009-2011 Your File System, Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * - Redistributions of source code must retain the above copyright notice,
10  *   this list of conditions and the following disclaimer.
11  * - Redistributions in binary form must reproduce the above copyright notice,
12  *   this list of conditions and the following disclaimer in the documentation
13  *   and/or other materials provided with the distribution.
14  * - Neither the name of Secure Endpoints Inc. nor the names of its contributors
15  *   may be used to endorse or promote products derived from this software without
16  *   specific prior written permission from Secure Endpoints, Inc. and
17  *   Your File System, Inc.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
22  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
23  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #include <afsconfig.h>
33 #include <afs/param.h>
34
35 #ifndef _WIN32_WINNT
36 #define _WIN32_WINNT 0x0500
37 #endif
38 #define _CRT_SECURE_NO_DEPRECATE
39 #define _CRT_NON_CONFORMING_SWPRINTFS
40 #define INITGUID        /* define AFS_AUTH_GUID_NO_PAG */
41
42 #include <ntstatus.h>
43 #define WIN32_NO_STATUS
44 #include <windows.h>
45
46 #include <roken.h>
47
48 #include <afs/stds.h>
49
50 #include <ntsecapi.h>
51 #include <sddl.h>
52 #pragma warning(push)
53 #pragma warning(disable: 4005)
54
55 #include <devioctl.h>
56
57 #include "..\\Common\\AFSUserDefines.h"
58 #include "..\\Common\\AFSUserStructs.h"
59
60 #pragma warning(pop)
61
62 #include <tchar.h>
63 #include <wchar.h>
64 #include <winbase.h>
65 #include <winreg.h>
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <stdarg.h>
70 #include <strsafe.h>
71
72 #include "afsd.h"
73 #include "smb.h"
74 #include "cm_btree.h"
75 #include "msrpc.h"
76 #include <RDRPrototypes.h>
77 #include <RDRIoctl.h>
78 #include <RDRPipe.h>
79
80 static CHAR * RDR_extentBaseAddress = NULL;
81
82 void
83 RDR_InitReq(cm_req_t *reqp, BOOL bWow64)
84 {
85     cm_InitReq(reqp);
86     reqp->flags |= CM_REQ_SOURCE_REDIR;
87     if (bWow64)
88         reqp->flags |= CM_REQ_WOW64;
89 }
90
91 void
92 RDR_fid2FID( cm_fid_t *fid, AFSFileID *FileId)
93 {
94     FileId->Cell = fid->cell;
95     FileId->Volume = fid->volume;
96     FileId->Vnode = fid->vnode;
97     FileId->Unique = fid->unique;
98     FileId->Hash = fid->hash;
99 }
100
101 void
102 RDR_FID2fid( AFSFileID *FileId, cm_fid_t *fid)
103 {
104     fid->cell = FileId->Cell;
105     fid->volume = FileId->Volume;
106     fid->vnode = FileId->Vnode;
107     fid->unique = FileId->Unique;
108     fid->hash = FileId->Hash;
109 }
110
111 DWORD
112 RDR_SetInitParams( OUT AFSRedirectorInitInfo **ppRedirInitInfo, OUT DWORD * pRedirInitInfoLen )
113 {
114     extern char cm_CachePath[];
115     extern cm_config_data_t cm_data;
116     extern int smb_hideDotFiles;
117     size_t cm_CachePathLen = strlen(cm_CachePath);
118     size_t err;
119     DWORD TempPathLen = ExpandEnvironmentStringsW(L"%TEMP%", NULL, 0);
120     MEMORYSTATUSEX memStatus;
121     DWORD maxMemoryCacheSize;
122
123     memStatus.dwLength = sizeof(memStatus);
124     if (GlobalMemoryStatusEx(&memStatus)) {
125         /*
126          * Use the memory extent interface in the afs redirector
127          * whenever the cache size is less than equal to 10% of
128          * physical memory.  Do not use too much because this memory
129          * will be locked by the redirector so it can't be swapped
130          * out.
131          */
132         maxMemoryCacheSize = (DWORD)(memStatus.ullTotalPhys / 1024 / 10);
133     } else {
134         /*
135          * If we can't determine the amount of physical memory
136          * in the system, be conservative and limit the use of
137          * memory extent interface to 64MB data caches.
138          */
139         maxMemoryCacheSize = 65536;
140     }
141
142     *pRedirInitInfoLen = (DWORD) (sizeof(AFSRedirectorInitInfo) + (cm_CachePathLen + TempPathLen) * sizeof(WCHAR));
143     *ppRedirInitInfo = (AFSRedirectorInitInfo *)malloc(*pRedirInitInfoLen);
144     (*ppRedirInitInfo)->Flags = smb_hideDotFiles ? AFS_REDIR_INIT_FLAG_HIDE_DOT_FILES : 0;
145     (*ppRedirInitInfo)->Flags |= cm_shortNames ? 0 : AFS_REDIR_INIT_FLAG_DISABLE_SHORTNAMES;
146     (*ppRedirInitInfo)->MaximumChunkLength = cm_data.chunkSize;
147     (*ppRedirInitInfo)->GlobalFileId.Cell   = cm_data.rootFid.cell;
148     (*ppRedirInitInfo)->GlobalFileId.Volume = cm_data.rootFid.volume;
149     (*ppRedirInitInfo)->GlobalFileId.Vnode  = cm_data.rootFid.vnode;
150     (*ppRedirInitInfo)->GlobalFileId.Unique = cm_data.rootFid.unique;
151     (*ppRedirInitInfo)->GlobalFileId.Hash   = cm_data.rootFid.hash;
152     (*ppRedirInitInfo)->ExtentCount.QuadPart = cm_data.buf_nbuffers;
153     (*ppRedirInitInfo)->CacheBlockSize = cm_data.blockSize;
154     (*ppRedirInitInfo)->MaxPathLinkCount = MAX_FID_COUNT;
155     (*ppRedirInitInfo)->NameArrayLength = MAX_FID_COUNT;
156     if (cm_virtualCache || cm_data.bufferSize <= maxMemoryCacheSize) {
157         osi_Log0(afsd_logp, "RDR_SetInitParams Initializing Memory Extent Interface");
158         (*ppRedirInitInfo)->MemoryCacheOffset.QuadPart = (LONGLONG)cm_data.bufDataBaseAddress;
159         (*ppRedirInitInfo)->MemoryCacheLength.QuadPart = cm_data.bufEndOfData - cm_data.bufDataBaseAddress;
160         (*ppRedirInitInfo)->CacheFileNameLength = 0;
161         RDR_extentBaseAddress = cm_data.bufDataBaseAddress;
162     } else {
163         (*ppRedirInitInfo)->MemoryCacheOffset.QuadPart = 0;
164         (*ppRedirInitInfo)->MemoryCacheLength.QuadPart = 0;
165         (*ppRedirInitInfo)->CacheFileNameLength = (ULONG) (cm_CachePathLen * sizeof(WCHAR));
166         err = mbstowcs((*ppRedirInitInfo)->CacheFileName, cm_CachePath, (cm_CachePathLen + 1) *sizeof(WCHAR));
167         if (err == -1) {
168             free(*ppRedirInitInfo);
169             osi_Log0(afsd_logp, "RDR_SetInitParams Invalid Object Name");
170             return STATUS_OBJECT_NAME_INVALID;
171         }
172         RDR_extentBaseAddress = cm_data.baseAddress;
173     }
174     (*ppRedirInitInfo)->DumpFileLocationOffset = FIELD_OFFSET(AFSRedirectorInitInfo, CacheFileName) + (*ppRedirInitInfo)->CacheFileNameLength;
175     (*ppRedirInitInfo)->DumpFileLocationLength = (TempPathLen - 1) * sizeof(WCHAR);
176     ExpandEnvironmentStringsW(L"%TEMP%",
177                               (LPWSTR)(((PBYTE)(*ppRedirInitInfo)) + (*ppRedirInitInfo)->DumpFileLocationOffset),
178                               TempPathLen);
179
180     osi_Log0(afsd_logp,"RDR_SetInitParams Success");
181     return 0;
182 }
183
184 static wchar_t cname[MAX_COMPUTERNAME_LENGTH+1] = L"";
185
186 cm_user_t *
187 RDR_GetLocalSystemUser( void)
188 {
189     smb_username_t *unp;
190     cm_user_t *userp = NULL;
191
192     if ( cname[0] == '\0') {
193         int len = MAX_COMPUTERNAME_LENGTH+1;
194         GetComputerNameW(cname, &len);
195         _wcsupr(cname);
196     }
197     unp = smb_FindUserByName(NTSID_LOCAL_SYSTEM, cname, SMB_FLAG_CREATE);
198     lock_ObtainMutex(&unp->mx);
199     if (!unp->userp)
200         unp->userp = cm_NewUser();
201     unp->flags |= SMB_USERNAMEFLAG_SID;
202     lock_ReleaseMutex(&unp->mx);
203     userp = unp->userp;
204     cm_HoldUser(userp);
205     smb_ReleaseUsername(unp);
206
207     if (!userp) {
208         userp = cm_rootUserp;
209         cm_HoldUser(userp);
210     }
211
212     return userp;
213 }
214
215 cm_user_t *
216 RDR_UserFromCommRequest( IN AFSCommRequest *RequestBuffer)
217 {
218
219     return RDR_UserFromAuthGroup( &RequestBuffer->AuthGroup);
220 }
221
222 cm_user_t *
223 RDR_UserFromAuthGroup( IN GUID *pGuid)
224 {
225     smb_username_t *unp;
226     cm_user_t * userp = NULL;
227     RPC_WSTR UuidString = NULL;
228
229     if (UuidToStringW((UUID *)pGuid, &UuidString) != RPC_S_OK)
230         goto done;
231
232     if ( cname[0] == '\0') {
233         int len = MAX_COMPUTERNAME_LENGTH+1;
234         GetComputerNameW(cname, &len);
235         _wcsupr(cname);
236     }
237
238     unp = smb_FindUserByName(UuidString, cname, SMB_FLAG_CREATE);
239     lock_ObtainMutex(&unp->mx);
240     if (!unp->userp) {
241         unp->userp = cm_NewUser();
242         memcpy(&unp->userp->authgroup, pGuid, sizeof(GUID));
243     }
244     unp->flags |= SMB_USERNAMEFLAG_SID;
245     lock_ReleaseMutex(&unp->mx);
246     userp = unp->userp;
247     cm_HoldUser(userp);
248     smb_ReleaseUsername(unp);
249
250   done:
251     if (!userp) {
252         userp = cm_rootUserp;
253         cm_HoldUser(userp);
254     }
255
256     osi_Log2(afsd_logp, "RDR_UserFromCommRequest Guid %S userp = 0x%p",
257              osi_LogSaveStringW(afsd_logp, UuidString),
258              userp);
259
260     if (UuidString)
261         RpcStringFreeW(&UuidString);
262
263     return userp;
264 }
265
266 void
267 RDR_ReleaseUser( IN cm_user_t *userp )
268 {
269     osi_Log1(afsd_logp, "RDR_ReleaseUser userp = 0x%p", userp);
270     cm_ReleaseUser(userp);
271 }
272
273
274 /*
275  * RDR_FlagScpInUse flags the scp with CM_SCACHEFLAG_RDR_IN_USE
276  */
277 static void
278 RDR_FlagScpInUse( IN cm_scache_t *scp, IN BOOL bLocked )
279 {
280     if (!bLocked)
281         lock_ObtainWrite(&scp->rw);
282
283     lock_AssertWrite(&scp->rw);
284     scp->flags |= CM_SCACHEFLAG_RDR_IN_USE;
285
286     if (!bLocked)
287         lock_ReleaseWrite(&scp->rw);
288 }
289
290 /*
291  * Obtain the status information for the specified object using
292  * an inline bulk status rpc.  cm_BPlusDirEnumBulkStatOne() will
293  * obtain current status for the directory object, the object
294  * which is the focus of the inquiry and as many other objects
295  * in the directory for which there are not callbacks registered
296  * since we are likely to be asked for other objects in the directory.
297  */
298 static afs_uint32
299 RDR_BulkStatLookup( cm_scache_t *dscp,
300                     cm_scache_t *scp,
301                     cm_user_t   *userp,
302                     cm_req_t    *reqp)
303 {
304     cm_direnum_t *      enump = NULL;
305     afs_uint32  code = 0;
306     cm_dirOp_t    dirop;
307
308     code = cm_BeginDirOp(dscp, userp, reqp, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
309     if (code == 0) {
310         code = cm_BPlusDirEnumerate(dscp, userp, reqp, TRUE, NULL, TRUE, &enump);
311         if (code) {
312             osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BPlusDirEnumerate failure code=0x%x",
313                       code);
314         }
315         cm_EndDirOp(&dirop);
316     } else {
317         osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BeginDirOp failure code=0x%x",
318                   code);
319     }
320
321     if (enump)
322     {
323         code = cm_BPlusDirEnumBulkStatOne(enump, scp);
324         if (code) {
325             osi_Log1(afsd_logp, "RDR_BulkStatLookup cm_BPlusDirEnumBulkStatOne failure code=0x%x",
326                       code);
327         }
328         cm_BPlusDirFreeEnumeration(enump);
329     }
330
331     return code;
332 }
333
334
335 #define RDR_POP_FOLLOW_MOUNTPOINTS 0x01
336 #define RDR_POP_EVALUATE_SYMLINKS  0x02
337 #define RDR_POP_WOW64              0x04
338 #define RDR_POP_NO_GETSTATUS       0x08
339
340 static afs_uint32
341 RDR_PopulateCurrentEntry( IN  AFSDirEnumEntry * pCurrentEntry,
342                           IN  DWORD             dwMaxEntryLength,
343                           IN  cm_scache_t     * dscp,
344                           IN  cm_scache_t     * scp,
345                           IN  cm_user_t       * userp,
346                           IN  cm_req_t        * reqp,
347                           IN  wchar_t         * name,
348                           IN  wchar_t         * shortName,
349                           IN  DWORD             dwFlags,
350                           IN  afs_uint32        cmError,
351                           OUT AFSDirEnumEntry **ppNextEntry,
352                           OUT DWORD           * pdwRemainingLength)
353 {
354     FILETIME ft;
355     WCHAR *  wname, *wtarget;
356     size_t   len;
357     DWORD      dwEntryLength;
358     afs_uint32 code = 0, code2 = 0;
359     BOOL          bMustFake = FALSE;
360
361     osi_Log5(afsd_logp, "RDR_PopulateCurrentEntry dscp=0x%p scp=0x%p name=%S short=%S flags=0x%x",
362              dscp, scp, osi_LogSaveStringW(afsd_logp, name),
363              osi_LogSaveStringW(afsd_logp, shortName), dwFlags);
364     osi_Log1(afsd_logp, "... maxLength=%d", dwMaxEntryLength);
365
366     if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
367         if (ppNextEntry)
368             *ppNextEntry = pCurrentEntry;
369         if (pdwRemainingLength)
370             *pdwRemainingLength = dwMaxEntryLength;
371         osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry Not Enough Room for Entry %d < %d",
372                  dwMaxEntryLength, sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t));
373         return CM_ERROR_TOOBIG;
374     }
375
376     if (!name)
377         name = L"";
378     if (!shortName)
379         shortName = L"";
380
381     dwEntryLength = sizeof(AFSDirEnumEntry);
382
383     lock_ObtainWrite(&scp->rw);
384     if (dwFlags & RDR_POP_NO_GETSTATUS) {
385         if (!cm_HaveCallback(scp))
386             bMustFake = TRUE;
387     } else {
388 #ifdef AFS_FREELANCE_CLIENT
389         if (scp->fid.cell == AFS_FAKE_ROOT_CELL_ID && scp->fid.volume == AFS_FAKE_ROOT_VOL_ID) {
390             /*
391              * If the FID is from the Freelance Local Root always perform
392              * a single item status check.
393              */
394             code = cm_SyncOp( scp, NULL, userp, reqp, 0,
395                               CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
396             if (code) {
397                 lock_ReleaseWrite(&scp->rw);
398                 osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_SyncOp failed for scp=0x%p code=0x%x",
399                          scp, code);
400                 return code;
401             }
402         } else
403 #endif
404         {
405             /*
406              * For non-Freelance objects, check to see if we have current
407              * status information.  If not, perform a bulk status lookup of multiple
408              * entries in order to reduce the number of RPCs issued to the file server.
409              */
410             if (cm_EAccesFindEntry(userp, &scp->fid))
411                 bMustFake = TRUE;
412             else if (!cm_HaveCallback(scp)) {
413                 lock_ReleaseWrite(&scp->rw);
414                 code = RDR_BulkStatLookup(dscp, scp, userp, reqp);
415                 if (code) {
416                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry RDR_BulkStatLookup failed for scp=0x%p code=0x%x",
417                              scp, code);
418                     return code;
419                 }
420                 lock_ObtainWrite(&scp->rw);
421                 /*
422                  * RDR_BulkStatLookup can succeed but it may be the case that there
423                  * still is not valid status info.  If we get this far, generate fake
424                  * status info.
425                  */
426                 if (!cm_HaveCallback(scp))
427                     bMustFake = TRUE;
428             }
429         }
430     }
431
432     /* Populate the error code */
433     smb_MapNTError(cmError, &pCurrentEntry->NTStatus, TRUE);
434
435     /* Populate the real or fake data */
436     pCurrentEntry->FileId.Cell = scp->fid.cell;
437     pCurrentEntry->FileId.Volume = scp->fid.volume;
438     pCurrentEntry->FileId.Vnode = scp->fid.vnode;
439     pCurrentEntry->FileId.Unique = scp->fid.unique;
440     pCurrentEntry->FileId.Hash = scp->fid.hash;
441
442     pCurrentEntry->FileType = scp->fileType;
443
444     pCurrentEntry->DataVersion.QuadPart = scp->dataVersion;
445
446     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
447         scp->fid.volume==AFS_FAKE_ROOT_VOL_ID) {
448         cm_LargeSearchTimeFromUnixTime(&ft, MAX_AFS_UINT32);
449     } else {
450         cm_LargeSearchTimeFromUnixTime(&ft, scp->cbExpires);
451     }
452     pCurrentEntry->Expiration.LowPart = ft.dwLowDateTime;
453     pCurrentEntry->Expiration.HighPart = ft.dwHighDateTime;
454
455     if (bMustFake) {
456         /* 1969-12-31 23:59:59 +00 */
457         ft.dwHighDateTime = 0x19DB200;
458         ft.dwLowDateTime = 0x5BB78980;
459     } else
460         cm_LargeSearchTimeFromUnixTime(&ft, scp->clientModTime);
461     pCurrentEntry->CreationTime.LowPart = ft.dwLowDateTime;
462     pCurrentEntry->CreationTime.HighPart = ft.dwHighDateTime;
463     pCurrentEntry->LastAccessTime = pCurrentEntry->CreationTime;
464     pCurrentEntry->LastWriteTime = pCurrentEntry->CreationTime;
465     pCurrentEntry->ChangeTime = pCurrentEntry->CreationTime;
466
467     pCurrentEntry->EndOfFile = scp->length;
468     pCurrentEntry->AllocationSize = scp->length;
469
470     if (bMustFake) {
471         switch (scp->fileType) {
472         case CM_SCACHETYPE_DIRECTORY:
473             pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY;
474             break;
475         case CM_SCACHETYPE_MOUNTPOINT:
476         case CM_SCACHETYPE_INVALID:
477             pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY | SMB_ATTR_REPARSE_POINT;
478             break;
479         case CM_SCACHETYPE_SYMLINK:
480             if (cm_TargetPerceivedAsDirectory(scp->mountPointStringp))
481                 pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY | SMB_ATTR_REPARSE_POINT;
482             else
483                 pCurrentEntry->FileAttributes = SMB_ATTR_REPARSE_POINT;
484             break;
485         default:
486             /* if we get here we either have a normal file
487             * or we have a file for which we have never
488             * received status info.  In this case, we can
489             * check the even/odd value of the entry's vnode.
490             * odd means it is to be treated as a directory
491             * and even means it is to be treated as a file.
492             */
493             if (scp->fid.vnode & 0x1)
494                 pCurrentEntry->FileAttributes = SMB_ATTR_DIRECTORY;
495             else
496                 pCurrentEntry->FileAttributes = SMB_ATTR_NORMAL;
497         }
498     } else
499         pCurrentEntry->FileAttributes = smb_ExtAttributes(scp);
500     pCurrentEntry->EaSize = 0;
501     pCurrentEntry->Links = scp->linkCount;
502
503     len = wcslen(shortName);
504     wcsncpy(pCurrentEntry->ShortName, shortName, len);
505     pCurrentEntry->ShortNameLength = (CCHAR)(len * sizeof(WCHAR));
506
507     pCurrentEntry->FileNameOffset = sizeof(AFSDirEnumEntry);
508     len = wcslen(name);
509     wname = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->FileNameOffset);
510     wcsncpy(wname, name, len);
511     pCurrentEntry->FileNameLength = (ULONG)(sizeof(WCHAR) * len);
512
513     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntry scp=0x%p fileType=%d dv=%u",
514               scp, scp->fileType, (afs_uint32)scp->dataVersion);
515
516     if (!(dwFlags & RDR_POP_NO_GETSTATUS))
517         cm_SyncOpDone( scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
518
519     if ((dwFlags & RDR_POP_NO_GETSTATUS) || !cm_HaveCallback(scp)) {
520         pCurrentEntry->TargetNameOffset = 0;
521         pCurrentEntry->TargetNameLength = 0;
522     }
523     else
524     switch (scp->fileType) {
525     case CM_SCACHETYPE_MOUNTPOINT:
526         if (dwFlags & RDR_POP_FOLLOW_MOUNTPOINTS) {
527             if ((code2 = cm_ReadMountPoint(scp, userp, reqp)) == 0) {
528                 cm_scache_t *targetScp = NULL;
529
530                 pCurrentEntry->TargetNameOffset = pCurrentEntry->FileNameOffset + pCurrentEntry->FileNameLength;
531                 len = strlen(scp->mountPointStringp);
532                 wtarget = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->TargetNameOffset);
533
534 #ifdef UNICODE
535                 cch = MultiByteToWideChar( CP_UTF8, 0, scp->mountPointStringp,
536                                            len * sizeof(char),
537                                            wtarget,
538                                            len * sizeof(WCHAR));
539 #else
540                 mbstowcs(wtarget, scp->mountPointStringp, len);
541 #endif
542                 pCurrentEntry->TargetNameLength = (ULONG)(sizeof(WCHAR) * len);
543
544                 code2 = cm_FollowMountPoint(scp, dscp, userp, reqp, &targetScp);
545
546                 if (code2 == 0) {
547                     pCurrentEntry->TargetFileId.Cell = targetScp->fid.cell;
548                     pCurrentEntry->TargetFileId.Volume = targetScp->fid.volume;
549                     pCurrentEntry->TargetFileId.Vnode = targetScp->fid.vnode;
550                     pCurrentEntry->TargetFileId.Unique = targetScp->fid.unique;
551                     pCurrentEntry->TargetFileId.Hash = targetScp->fid.hash;
552
553                     osi_Log4(afsd_logp, "RDR_PopulateCurrentEntry target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
554                               pCurrentEntry->TargetFileId.Cell, pCurrentEntry->TargetFileId.Volume,
555                               pCurrentEntry->TargetFileId.Vnode, pCurrentEntry->TargetFileId.Unique);
556
557                     cm_ReleaseSCache(targetScp);
558                 } else {
559                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_FollowMountPoint failed scp=0x%p code=0x%x",
560                               scp, code2);
561                 }
562             } else {
563                 osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_ReadMountPoint failed scp=0x%p code=0x%x",
564                           scp, code2);
565             }
566         }
567         break;
568     case CM_SCACHETYPE_SYMLINK:
569     case CM_SCACHETYPE_DFSLINK:
570         {
571             pCurrentEntry->TargetNameOffset = pCurrentEntry->FileNameOffset + pCurrentEntry->FileNameLength;
572             wtarget = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->TargetNameOffset);
573
574             if (dwFlags & RDR_POP_EVALUATE_SYMLINKS) {
575                 char * mp;
576
577                 code2 = cm_HandleLink(scp, userp, reqp);
578                 if (code2 == 0) {
579                     mp = scp->mountPointStringp;
580                     len = strlen(mp);
581                     if ( len != 0 ) {
582                         /* Strip off the msdfs: prefix from the target name for the file system */
583                         if (scp->fileType == CM_SCACHETYPE_DFSLINK) {
584                             osi_Log0(afsd_logp, "RDR_PopulateCurrentEntry DFSLink Detected");
585                             pCurrentEntry->FileType = scp->fileType;
586
587                             if (!strncmp("msdfs:", mp, 6)) {
588                                 mp += 6;
589                                 len -= 6;
590                             }
591                         }
592                         /* only send one slash to the redirector */
593                         if (mp[0] == '\\' && mp[1] == '\\') {
594                             mp++;
595                             len--;
596                         }
597 #ifdef UNICODE
598                         cch = MultiByteToWideChar( CP_UTF8, 0, mp,
599                                                    len * sizeof(char),
600                                                    wtarget,
601                                                    len * sizeof(WCHAR));
602 #else
603                         mbstowcs(wtarget, mp, len);
604 #endif
605                     }
606                     pCurrentEntry->TargetNameLength = (ULONG)(sizeof(WCHAR) * len);
607                 } else {
608                     osi_Log2(afsd_logp, "RDR_PopulateCurrentEntry cm_HandleLink failed scp=0x%p code=0x%x",
609                              scp, code2);
610                 }
611             }
612
613         }
614         break;
615
616     default:
617         pCurrentEntry->TargetNameOffset = 0;
618         pCurrentEntry->TargetNameLength = 0;
619     }
620     lock_ReleaseWrite(&scp->rw);
621
622     dwEntryLength += pCurrentEntry->FileNameLength + pCurrentEntry->TargetNameLength;
623     dwEntryLength += (dwEntryLength % 8) ? 8 - (dwEntryLength % 8) : 0;   /* quad align */
624     if (ppNextEntry)
625         *ppNextEntry = (AFSDirEnumEntry *)((PBYTE)pCurrentEntry + dwEntryLength);
626     if (pdwRemainingLength)
627         *pdwRemainingLength = dwMaxEntryLength - dwEntryLength;
628
629     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntry Success FileNameLength=%d TargetNameLength=%d RemainingLength=%d",
630               pCurrentEntry->FileNameLength, pCurrentEntry->TargetNameLength, *pdwRemainingLength);
631
632     return code;
633 }
634
635 static afs_uint32
636 RDR_PopulateCurrentEntryNoScp( IN  AFSDirEnumEntry * pCurrentEntry,
637                                IN  DWORD             dwMaxEntryLength,
638                                IN  cm_scache_t     * dscp,
639                                IN  cm_fid_t        * fidp,
640                                IN  cm_user_t       * userp,
641                                IN  cm_req_t        * reqp,
642                                IN  wchar_t         * name,
643                                IN  wchar_t         * shortName,
644                                IN  DWORD             dwFlags,
645                                IN  afs_uint32        cmError,
646                                OUT AFSDirEnumEntry **ppNextEntry,
647                                OUT DWORD           * pdwRemainingLength)
648 {
649     FILETIME ft;
650     WCHAR *  wname;
651     size_t   len;
652     DWORD      dwEntryLength;
653     afs_uint32 code = 0, code2 = 0;
654
655     osi_Log4(afsd_logp, "RDR_PopulateCurrentEntryNoEntry dscp=0x%p name=%S short=%S flags=0x%x",
656              dscp, osi_LogSaveStringW(afsd_logp, name),
657              osi_LogSaveStringW(afsd_logp, shortName), dwFlags);
658     osi_Log1(afsd_logp, "... maxLength=%d", dwMaxEntryLength);
659
660     if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
661         if (ppNextEntry)
662             *ppNextEntry = pCurrentEntry;
663         if (pdwRemainingLength)
664             *pdwRemainingLength = dwMaxEntryLength;
665         osi_Log2(afsd_logp, "RDR_PopulateCurrentEntryNoEntry Not Enough Room for Entry %d < %d",
666                  dwMaxEntryLength, sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t));
667         return CM_ERROR_TOOBIG;
668     }
669
670     if (!name)
671         name = L"";
672     if (!shortName)
673         shortName = L"";
674
675     dwEntryLength = sizeof(AFSDirEnumEntry);
676
677     /* Populate the error code */
678     smb_MapNTError(cmError, &pCurrentEntry->NTStatus, TRUE);
679
680     /* Populate the fake data */
681     pCurrentEntry->FileId.Cell = fidp->cell;
682     pCurrentEntry->FileId.Volume = fidp->volume;
683     pCurrentEntry->FileId.Vnode = fidp->vnode;
684     pCurrentEntry->FileId.Unique = fidp->unique;
685     pCurrentEntry->FileId.Hash = fidp->hash;
686
687     pCurrentEntry->FileType = CM_SCACHETYPE_UNKNOWN;
688
689     pCurrentEntry->DataVersion.QuadPart = CM_SCACHE_VERSION_BAD;
690
691     cm_LargeSearchTimeFromUnixTime(&ft, 0);
692     pCurrentEntry->Expiration.LowPart = ft.dwLowDateTime;
693     pCurrentEntry->Expiration.HighPart = ft.dwHighDateTime;
694
695     cm_LargeSearchTimeFromUnixTime(&ft, 0);
696     pCurrentEntry->CreationTime.LowPart = ft.dwLowDateTime;
697     pCurrentEntry->CreationTime.HighPart = ft.dwHighDateTime;
698     pCurrentEntry->LastAccessTime = pCurrentEntry->CreationTime;
699     pCurrentEntry->LastWriteTime = pCurrentEntry->CreationTime;
700     pCurrentEntry->ChangeTime = pCurrentEntry->CreationTime;
701
702     pCurrentEntry->EndOfFile.QuadPart = 0;
703     pCurrentEntry->AllocationSize.QuadPart = 0;
704     pCurrentEntry->FileAttributes = 0;
705     pCurrentEntry->EaSize = 0;
706     pCurrentEntry->Links = 0;
707
708     len = wcslen(shortName);
709     wcsncpy(pCurrentEntry->ShortName, shortName, len);
710     pCurrentEntry->ShortNameLength = (CCHAR)(len * sizeof(WCHAR));
711
712     pCurrentEntry->FileNameOffset = sizeof(AFSDirEnumEntry);
713     len = wcslen(name);
714     wname = (WCHAR *)((PBYTE)pCurrentEntry + pCurrentEntry->FileNameOffset);
715     wcsncpy(wname, name, len);
716     pCurrentEntry->FileNameLength = (ULONG)(sizeof(WCHAR) * len);
717
718     pCurrentEntry->TargetNameOffset = 0;
719     pCurrentEntry->TargetNameLength = 0;
720
721     dwEntryLength += pCurrentEntry->FileNameLength + pCurrentEntry->TargetNameLength;
722     dwEntryLength += (dwEntryLength % 8) ? 8 - (dwEntryLength % 8) : 0;   /* quad align */
723     if (ppNextEntry)
724         *ppNextEntry = (AFSDirEnumEntry *)((PBYTE)pCurrentEntry + dwEntryLength);
725     if (pdwRemainingLength)
726         *pdwRemainingLength = dwMaxEntryLength - dwEntryLength;
727
728     osi_Log3(afsd_logp, "RDR_PopulateCurrentEntryNoScp Success FileNameLength=%d TargetNameLength=%d RemainingLength=%d",
729               pCurrentEntry->FileNameLength, pCurrentEntry->TargetNameLength, *pdwRemainingLength);
730
731     return code;
732 }
733
734 void
735 RDR_EnumerateDirectory( IN cm_user_t *userp,
736                         IN AFSFileID DirID,
737                         IN AFSDirQueryCB *QueryCB,
738                         IN BOOL bWow64,
739                         IN BOOL bSkipStatus,
740                         IN DWORD ResultBufferLength,
741                         IN OUT AFSCommResult **ResultCB)
742 {
743     DWORD status;
744     cm_direnum_t *      enump = NULL;
745     AFSDirEnumResp  * pDirEnumResp;
746     AFSDirEnumEntry * pCurrentEntry;
747     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
748     DWORD             dwMaxEntryLength;
749     afs_uint32  code = 0;
750     cm_fid_t      fid;
751     cm_scache_t * dscp = NULL;
752     cm_req_t      req;
753
754     RDR_InitReq(&req, bWow64);
755
756     osi_Log4(afsd_logp, "RDR_EnumerateDirectory FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
757              DirID.Cell, DirID.Volume, DirID.Vnode, DirID.Unique);
758
759     *ResultCB = (AFSCommResult *)malloc(size);
760     if (!(*ResultCB)) {
761         osi_Log0(afsd_logp, "RDR_EnumerateDirectory Out of Memory");
762         return;
763     }
764
765     memset(*ResultCB, 0, size);
766
767     if (QueryCB->EnumHandle == (ULONG_PTR)-1) {
768         osi_Log0(afsd_logp, "RDR_EnumerateDirectory No More Entries");
769         (*ResultCB)->ResultStatus = STATUS_NO_MORE_ENTRIES;
770         (*ResultCB)->ResultBufferLength = 0;
771         return;
772     }
773
774     (*ResultCB)->ResultBufferLength = dwMaxEntryLength = ResultBufferLength;
775     if (ResultBufferLength) {
776         pDirEnumResp = (AFSDirEnumResp *)&(*ResultCB)->ResultData;
777         pCurrentEntry = (AFSDirEnumEntry *)&pDirEnumResp->Entry;
778         dwMaxEntryLength -= FIELD_OFFSET( AFSDirEnumResp, Entry);      /* AFSDirEnumResp */
779     }
780
781     if (DirID.Cell != 0) {
782         fid.cell   = DirID.Cell;
783         fid.volume = DirID.Volume;
784         fid.vnode  = DirID.Vnode;
785         fid.unique = DirID.Unique;
786         fid.hash   = DirID.Hash;
787
788         code = cm_GetSCache(&fid, NULL, &dscp, userp, &req);
789         if (code) {
790             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
791             (*ResultCB)->ResultStatus = status;
792             osi_Log2(afsd_logp, "RDR_EnumerateDirectory cm_GetSCache failure code=0x%x status=0x%x",
793                       code, status);
794             return;
795         }
796     } else {
797         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
798         osi_Log0(afsd_logp, "RDR_EnumerateDirectory Object Name Invalid - Cell = 0");
799         return;
800     }
801
802     /* get the directory size */
803     lock_ObtainWrite(&dscp->rw);
804     code = cm_SyncOp(dscp, NULL, userp, &req, PRSFS_LOOKUP,
805                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
806     if (code) {
807         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
808         (*ResultCB)->ResultStatus = status;
809         lock_ReleaseWrite(&dscp->rw);
810         cm_ReleaseSCache(dscp);
811         osi_Log2(afsd_logp, "RDR_EnumerateDirectory cm_SyncOp failure code=0x%x status=0x%x",
812                   code, status);
813         return;
814     }
815
816     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
817     lock_ReleaseWrite(&dscp->rw);
818
819     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
820         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
821         cm_ReleaseSCache(dscp);
822         osi_Log1(afsd_logp, "RDR_EnumerateDirectory Not a Directory dscp=0x%p",
823                  dscp);
824         return;
825     }
826
827     osi_Log1(afsd_logp, "RDR_EnumerateDirectory dv=%u", (afs_uint32)dscp->dataVersion);
828
829     /*
830      * If there is no enumeration handle, then this is a new query
831      * and we must perform an enumeration for the specified object.
832      */
833     if (QueryCB->EnumHandle == (ULONG_PTR)NULL) {
834         cm_dirOp_t    dirop;
835
836         code = cm_BeginDirOp(dscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
837         if (code == 0) {
838             code = cm_BPlusDirEnumerate(dscp, userp, &req,
839                                         TRUE /* dir locked */, NULL /* no mask */,
840                                         TRUE /* fetch status? */, &enump);
841             if (code) {
842                 osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BPlusDirEnumerate failure code=0x%x",
843                           code);
844             }
845             cm_EndDirOp(&dirop);
846         } else {
847             osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BeginDirOp failure code=0x%x",
848                       code);
849         }
850     } else {
851         enump = (cm_direnum_t *)QueryCB->EnumHandle;
852     }
853
854     if (enump) {
855         if (ResultBufferLength == 0) {
856             code = cm_BPlusDirEnumBulkStat(enump);
857             if (code) {
858                 osi_Log1(afsd_logp, "RDR_EnumerateDirectory cm_BPlusDirEnumBulkStat failure code=0x%x",
859                           code);
860             }
861         } else {
862             cm_direnum_entry_t * entryp = NULL;
863
864             pDirEnumResp->SnapshotDataVersion.QuadPart = enump->dataVersion;
865
866           getnextentry:
867             if (dwMaxEntryLength < sizeof(AFSDirEnumEntry) + (MAX_PATH + MOUNTPOINTLEN) * sizeof(wchar_t)) {
868                 osi_Log0(afsd_logp, "RDR_EnumerateDirectory out of space, returning");
869                 goto outofspace;
870             }
871
872             code = cm_BPlusDirNextEnumEntry(enump, &entryp);
873
874             if ((code == 0 || code == CM_ERROR_STOPNOW) && entryp) {
875                 cm_scache_t *scp = NULL;
876                 int stopnow = (code == CM_ERROR_STOPNOW);
877
878                 if ( !wcscmp(L".", entryp->name) || !wcscmp(L"..", entryp->name) ) {
879                     osi_Log0(afsd_logp, "RDR_EnumerateDirectory skipping . or ..");
880                     if (stopnow)
881                         goto outofspace;
882                     goto getnextentry;
883                 }
884
885                 if (bSkipStatus) {
886                     code = cm_GetSCache(&entryp->fid, &dscp->fid, &scp, userp, &req);
887                     if (code) {
888                         osi_Log5(afsd_logp, "RDR_EnumerateDirectory cm_GetSCache failure cell %u vol %u vnode %u uniq %u code=0x%x",
889                                  entryp->fid.cell, entryp->fid.volume, entryp->fid.vnode, entryp->fid.unique, code);
890                     }
891                 } else {
892                     code = entryp->errorCode;
893                     scp = code ? NULL : cm_FindSCache(&entryp->fid);
894                 }
895
896                 if (scp) {
897                     code = RDR_PopulateCurrentEntry( pCurrentEntry, dwMaxEntryLength,
898                                                      dscp, scp, userp, &req,
899                                                      entryp->name,
900                                                      cm_shortNames && cm_Is8Dot3(entryp->name) ? NULL : entryp->shortName,
901                                                      (bWow64 ? RDR_POP_WOW64 : 0) |
902                                                      (bSkipStatus ? RDR_POP_NO_GETSTATUS : 0),
903                                                      code,
904                                                      &pCurrentEntry, &dwMaxEntryLength);
905                     cm_ReleaseSCache(scp);
906                 } else {
907                     code = RDR_PopulateCurrentEntryNoScp( pCurrentEntry, dwMaxEntryLength,
908                                                           dscp, &entryp->fid, userp, &req,
909                                                           entryp->name,
910                                                           cm_shortNames && cm_Is8Dot3(entryp->name) ? NULL : entryp->shortName,
911                                                           (bWow64 ? RDR_POP_WOW64 : 0),
912                                                           code,
913                                                           &pCurrentEntry, &dwMaxEntryLength);
914                 }
915                 if (stopnow)
916                     goto outofspace;
917                 goto getnextentry;
918             }
919         }
920     }
921
922   outofspace:
923
924     if (code || enump->next == enump->count || ResultBufferLength == 0) {
925         cm_BPlusDirFreeEnumeration(enump);
926         enump = (cm_direnum_t *)(ULONG_PTR)-1;
927     }
928
929     if (code == 0 || code == CM_ERROR_STOPNOW) {
930         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
931         osi_Log0(afsd_logp, "RDR_EnumerateDirectory SUCCESS");
932     } else {
933         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
934         (*ResultCB)->ResultStatus = status;
935         osi_Log2(afsd_logp, "RDR_EnumerateDirectory Failure code=0x%x status=0x%x",
936                   code, status);
937     }
938
939     if (ResultBufferLength) {
940         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwMaxEntryLength;
941
942         pDirEnumResp->EnumHandle = (ULONG_PTR) enump;
943         pDirEnumResp->CurrentDataVersion.QuadPart = dscp->dataVersion;
944     }
945
946     if (dscp)
947         cm_ReleaseSCache(dscp);
948
949     return;
950 }
951
952 void
953 RDR_EvaluateNodeByName( IN cm_user_t *userp,
954                         IN AFSFileID ParentID,
955                         IN WCHAR   *FileNameCounted,
956                         IN DWORD    FileNameLength,
957                         IN BOOL     CaseSensitive,
958                         IN BOOL     bWow64,
959                         IN BOOL     bHoldFid,
960                         IN BOOL     bNoFollow,
961                         IN DWORD    ResultBufferLength,
962                         IN OUT AFSCommResult **ResultCB)
963 {
964     AFSFileEvalResultCB *pEvalResultCB = NULL;
965     AFSDirEnumEntry * pCurrentEntry;
966     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
967     afs_uint32  code = 0;
968     cm_scache_t * scp = NULL;
969     cm_scache_t * dscp = NULL;
970     cm_req_t      req;
971     cm_fid_t      parentFid;
972     DWORD         status;
973     DWORD         dwRemaining;
974     WCHAR       * wszName = NULL;
975     size_t        cbName;
976     BOOL          bVol = FALSE;
977     wchar_t       FileName[260];
978
979     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
980
981     RDR_InitReq(&req, bWow64);
982
983     osi_Log4(afsd_logp, "RDR_EvaluateNodeByName parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
984              ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
985
986     /* Allocate enough room to add a volume prefix if necessary */
987     cbName = FileNameLength + (CM_PREFIX_VOL_CCH + 1) * sizeof(WCHAR);
988     wszName = malloc(cbName);
989     if (!wszName) {
990         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Out of Memory");
991         return;
992     }
993     StringCbCopyNW(wszName, cbName, FileName, FileNameLength);
994     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, wszName));
995
996     *ResultCB = (AFSCommResult *)malloc(size);
997     if (!(*ResultCB)) {
998         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Out of Memory");
999         free(wszName);
1000         return;
1001     }
1002
1003     memset(*ResultCB, 0, size);
1004     (*ResultCB)->ResultBufferLength = 0;
1005     dwRemaining = ResultBufferLength;
1006     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1007         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1008         pCurrentEntry = &pEvalResultCB->DirEnum;
1009         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1010     }
1011
1012     if (ParentID.Cell != 0) {
1013         parentFid.cell   = ParentID.Cell;
1014         parentFid.volume = ParentID.Volume;
1015         parentFid.vnode  = ParentID.Vnode;
1016         parentFid.unique = ParentID.Unique;
1017         parentFid.hash   = ParentID.Hash;
1018
1019         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1020         if (code) {
1021             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1022             (*ResultCB)->ResultStatus = status;
1023             if ( status == STATUS_INVALID_HANDLE)
1024                 status = STATUS_OBJECT_PATH_INVALID;
1025             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName cm_GetSCache parentFID failure code=0x%x status=0x%x",
1026                       code, status);
1027             free(wszName);
1028             return;
1029         }
1030     } else {
1031         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1032         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName Object Name Invalid - Cell = 0");
1033         return;
1034     }
1035
1036     /* get the directory size */
1037     lock_ObtainWrite(&dscp->rw);
1038     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1039                      CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1040     if (code) {
1041         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1042         (*ResultCB)->ResultStatus = status;
1043         lock_ReleaseWrite(&dscp->rw);
1044         cm_ReleaseSCache(dscp);
1045         osi_Log3(afsd_logp, "RDR_EvaluateNodeByName cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1046                  dscp, code, status);
1047         free(wszName);
1048         return;
1049     }
1050     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1051     lock_ReleaseWrite(&dscp->rw);
1052
1053     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1054         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1055         cm_ReleaseSCache(dscp);
1056         osi_Log1(afsd_logp, "RDR_EvaluateNodeByName Not a Directory dscp=0x%p",
1057                  dscp);
1058         free(wszName);
1059         return;
1060     }
1061
1062     code = cm_Lookup(dscp, wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1063
1064     if ((code == CM_ERROR_NOSUCHPATH || code == CM_ERROR_NOSUCHFILE || code == CM_ERROR_BPLUS_NOMATCH) &&
1065          (wcschr(wszName, '%') != NULL || wcschr(wszName, '#') != NULL)) {
1066         /*
1067          * A volume reference:  <cell>{%,#}<volume> -> @vol:<cell>{%,#}<volume>
1068          */
1069         StringCchCopyNW(wszName, cbName, _C(CM_PREFIX_VOL), CM_PREFIX_VOL_CCH);
1070         StringCbCatNW(wszName, cbName, FileName, FileNameLength);
1071         bVol = TRUE;
1072
1073         code = cm_EvaluateVolumeReference(wszName, CM_FLAG_CHECKPATH, userp, &req, &scp);
1074     }
1075
1076     if (code == 0 && scp) {
1077         wchar_t shortName[13]=L"";
1078
1079         if (!cm_shortNames) {
1080             shortName[0] = L'\0';
1081         } else if (bVol) {
1082             cm_Gen8Dot3VolNameW(scp->fid.cell, scp->fid.volume, shortName, NULL);
1083         } else if (!cm_Is8Dot3(wszName)) {
1084             cm_dirFid_t dfid;
1085
1086             dfid.vnode = htonl(scp->fid.vnode);
1087             dfid.unique = htonl(scp->fid.unique);
1088
1089             cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1090         } else {
1091             shortName[0] = L'\0';
1092         }
1093
1094         code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1095                                         dscp, scp, userp, &req,
1096                                         FileName, shortName,
1097                                         (bWow64 ? RDR_POP_WOW64 : 0) |
1098                                         (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1099                                         0, NULL, &dwRemaining);
1100         if (bHoldFid)
1101             RDR_FlagScpInUse( scp, FALSE );
1102         cm_ReleaseSCache(scp);
1103
1104         if (code) {
1105             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1106             (*ResultCB)->ResultStatus = status;
1107             osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1108                       code, status);
1109         } else {
1110             pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1111             (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1112             (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1113             osi_Log0(afsd_logp, "RDR_EvaluateNodeByName SUCCESS");
1114         }
1115     } else if (code) {
1116         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1117         (*ResultCB)->ResultStatus = status;
1118         osi_Log2(afsd_logp, "RDR_EvaluateNodeByName FAILURE code=0x%x status=0x%x",
1119                  code, status);
1120     } else {
1121         (*ResultCB)->ResultStatus = STATUS_NO_SUCH_FILE;
1122         osi_Log0(afsd_logp, "RDR_EvaluateNodeByName No Such File");
1123     }
1124     cm_ReleaseSCache(dscp);
1125     free(wszName);
1126
1127     return;
1128 }
1129
1130 void
1131 RDR_EvaluateNodeByID( IN cm_user_t *userp,
1132                       IN AFSFileID ParentID,            /* not used */
1133                       IN AFSFileID SourceID,
1134                       IN BOOL      bWow64,
1135                       IN BOOL      bNoFollow,
1136                       IN BOOL      bHoldFid,
1137                       IN DWORD     ResultBufferLength,
1138                       IN OUT AFSCommResult **ResultCB)
1139 {
1140     AFSFileEvalResultCB *pEvalResultCB = NULL;
1141     AFSDirEnumEntry * pCurrentEntry = NULL;
1142     size_t size = ResultBufferLength ? sizeof(AFSCommResult) + ResultBufferLength - 1 : sizeof(AFSCommResult);
1143     afs_uint32  code = 0;
1144     cm_scache_t * scp = NULL;
1145     cm_scache_t * dscp = NULL;
1146     cm_req_t      req;
1147     cm_fid_t      Fid;
1148     cm_fid_t      parentFid;
1149     DWORD         status;
1150     DWORD         dwRemaining;
1151
1152     osi_Log4(afsd_logp, "RDR_EvaluateNodeByID source FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1153               SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1154     osi_Log4(afsd_logp, "... parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1155               ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1156
1157     *ResultCB = (AFSCommResult *)malloc(size);
1158     if (!(*ResultCB)) {
1159         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Out of Memory");
1160         return;
1161     }
1162
1163     memset(*ResultCB, 0, size);
1164     (*ResultCB)->ResultBufferLength = 0;
1165     dwRemaining = ResultBufferLength;
1166     if (ResultBufferLength >= sizeof( AFSFileEvalResultCB)) {
1167         pEvalResultCB = (AFSFileEvalResultCB *)&(*ResultCB)->ResultData;
1168         pCurrentEntry = &pEvalResultCB->DirEnum;
1169         dwRemaining -= (sizeof( AFSFileEvalResultCB) - sizeof( AFSDirEnumEntry));
1170     }
1171
1172     RDR_InitReq(&req, bWow64);
1173
1174     if (SourceID.Cell != 0) {
1175         cm_SetFid(&Fid, SourceID.Cell, SourceID.Volume, SourceID.Vnode, SourceID.Unique);
1176         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
1177         if (code) {
1178             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1179             (*ResultCB)->ResultStatus = status;
1180             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache SourceFID failure code=0x%x status=0x%x",
1181                       code, status);
1182             return;
1183         }
1184     } else {
1185         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
1186         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Name Invalid - Cell = 0");
1187         return;
1188     }
1189
1190     if (ParentID.Cell != 0) {
1191         cm_SetFid(&parentFid, ParentID.Cell, ParentID.Volume, ParentID.Vnode, ParentID.Unique);
1192         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1193         if (code) {
1194             cm_ReleaseSCache(scp);
1195             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1196             if ( status == STATUS_INVALID_HANDLE)
1197                 status = STATUS_OBJECT_PATH_INVALID;
1198             (*ResultCB)->ResultStatus = status;
1199             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1200                       code, status);
1201             return;
1202         }
1203     } else if (SourceID.Vnode == 1) {
1204         dscp = scp;
1205         cm_HoldSCache(dscp);
1206     } else if (scp->parentVnode) {
1207         cm_SetFid(&parentFid, SourceID.Cell, SourceID.Volume, scp->parentVnode, scp->parentUnique);
1208         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1209         if (code) {
1210             cm_ReleaseSCache(scp);
1211             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1212             if ( status == STATUS_INVALID_HANDLE)
1213                 status = STATUS_OBJECT_PATH_INVALID;
1214             (*ResultCB)->ResultStatus = status;
1215             osi_Log2(afsd_logp, "RDR_EvaluateNodeByID cm_GetSCache parentFID failure code=0x%x status=0x%x",
1216                       code, status);
1217             return;
1218         }
1219     } else {
1220         (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
1221         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID Object Path Invalid - Unknown Parent");
1222         return;
1223     }
1224
1225     /* Make sure the directory is current */
1226     lock_ObtainWrite(&dscp->rw);
1227     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1228                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1229     if (code) {
1230         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1231         (*ResultCB)->ResultStatus = status;
1232         lock_ReleaseWrite(&dscp->rw);
1233         cm_ReleaseSCache(dscp);
1234         cm_ReleaseSCache(scp);
1235         osi_Log3(afsd_logp, "RDR_EvaluateNodeByID cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1236                  dscp, code, status);
1237         return;
1238     }
1239
1240     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1241     lock_ReleaseWrite(&dscp->rw);
1242
1243     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1244         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1245         cm_ReleaseSCache(dscp);
1246         cm_ReleaseSCache(scp);
1247         osi_Log1(afsd_logp, "RDR_EvaluateNodeByID Not a Directory dscp=0x%p", dscp);
1248         return;
1249     }
1250
1251     code = RDR_PopulateCurrentEntry(pCurrentEntry, dwRemaining,
1252                                     dscp, scp, userp, &req, NULL, NULL,
1253                                     (bWow64 ? RDR_POP_WOW64 : 0) |
1254                                     (bNoFollow ? 0 : (RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS)),
1255                                     0, NULL, &dwRemaining);
1256
1257     if (bHoldFid)
1258         RDR_FlagScpInUse( scp, FALSE );
1259     cm_ReleaseSCache(scp);
1260     cm_ReleaseSCache(dscp);
1261
1262     if (code) {
1263         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1264         (*ResultCB)->ResultStatus = status;
1265         osi_Log2(afsd_logp, "RDR_EvaluateNodeByID FAILURE code=0x%x status=0x%x",
1266                  code, status);
1267     } else {
1268         pEvalResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1269
1270         (*ResultCB)->ResultStatus = STATUS_SUCCESS;
1271         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1272         osi_Log0(afsd_logp, "RDR_EvaluateNodeByID SUCCESS");
1273     }
1274     return;
1275 }
1276
1277 void
1278 RDR_CreateFileEntry( IN cm_user_t *userp,
1279                      IN WCHAR *FileNameCounted,
1280                      IN DWORD FileNameLength,
1281                      IN AFSFileCreateCB *CreateCB,
1282                      IN BOOL bWow64,
1283                      IN BOOL bHoldFid,
1284                      IN DWORD ResultBufferLength,
1285                      IN OUT AFSCommResult **ResultCB)
1286 {
1287     AFSFileCreateResultCB *pResultCB = NULL;
1288     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1289     cm_fid_t            parentFid;
1290     afs_uint32          code;
1291     cm_scache_t *       dscp = NULL;
1292     afs_uint32          flags = 0;
1293     cm_attr_t           setAttr;
1294     cm_scache_t *       scp = NULL;
1295     cm_req_t            req;
1296     DWORD               status;
1297     wchar_t             FileName[260];
1298
1299     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1300
1301     osi_Log4(afsd_logp, "RDR_CreateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1302               CreateCB->ParentId.Cell, CreateCB->ParentId.Volume,
1303               CreateCB->ParentId.Vnode, CreateCB->ParentId.Unique);
1304     osi_Log1(afsd_logp, "... name=%S", osi_LogSaveStringW(afsd_logp, FileName));
1305
1306     RDR_InitReq(&req, bWow64);
1307     memset(&setAttr, 0, sizeof(cm_attr_t));
1308
1309     *ResultCB = (AFSCommResult *)malloc(size);
1310     if (!(*ResultCB)) {
1311         osi_Log0(afsd_logp, "RDR_CreateFileEntry out of memory");
1312         return;
1313     }
1314
1315     memset( *ResultCB,
1316             '\0',
1317             size);
1318
1319     parentFid.cell   = CreateCB->ParentId.Cell;
1320     parentFid.volume = CreateCB->ParentId.Volume;
1321     parentFid.vnode  = CreateCB->ParentId.Vnode;
1322     parentFid.unique = CreateCB->ParentId.Unique;
1323     parentFid.hash   = CreateCB->ParentId.Hash;
1324
1325     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1326     if (code) {
1327         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1328         (*ResultCB)->ResultStatus = status;
1329         if ( status == STATUS_INVALID_HANDLE)
1330             status = STATUS_OBJECT_PATH_INVALID;
1331         osi_Log2(afsd_logp, "RDR_CreateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1332                   code, status);
1333         return;
1334     }
1335
1336     lock_ObtainWrite(&dscp->rw);
1337     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1338                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1339     if (code) {
1340         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1341         (*ResultCB)->ResultStatus = status;
1342         lock_ReleaseWrite(&dscp->rw);
1343         cm_ReleaseSCache(dscp);
1344         osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (1) dscp=0x%p code=0x%x status=0x%x",
1345                  dscp, code, status);
1346         return;
1347     }
1348
1349     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1350     lock_ReleaseWrite(&dscp->rw);
1351
1352     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1353         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1354         cm_ReleaseSCache(dscp);
1355         osi_Log1(afsd_logp, "RDR_CreateFileEntry Not a Directory dscp=0x%p",
1356                  dscp);
1357         return;
1358     }
1359
1360     /* Use current time */
1361     setAttr.mask = CM_ATTRMASK_CLIENTMODTIME;
1362     setAttr.clientModTime = time(NULL);
1363
1364     if (CreateCB->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1365         if (smb_unixModeDefaultDir) {
1366             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1367             setAttr.unixModeBits = smb_unixModeDefaultDir;
1368             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1369                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1370         }
1371
1372         code = cm_MakeDir(dscp, FileName, flags, &setAttr, userp, &req, &scp);
1373     } else {
1374         if (smb_unixModeDefaultFile) {
1375             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1376             setAttr.unixModeBits = smb_unixModeDefaultFile;
1377             if (CreateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)
1378                 setAttr.unixModeBits &= ~0222;          /* disable the write bits */
1379         }
1380
1381         setAttr.mask |= CM_ATTRMASK_LENGTH;
1382         setAttr.length.LowPart = CreateCB->AllocationSize.LowPart;
1383         setAttr.length.HighPart = CreateCB->AllocationSize.HighPart;
1384         code = cm_Create(dscp, FileName, flags, &setAttr, &scp, userp, &req);
1385     }
1386     if (code == 0) {
1387         wchar_t shortName[13]=L"";
1388         cm_dirFid_t dfid;
1389         DWORD dwRemaining;
1390
1391         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
1392
1393         (*ResultCB)->ResultBufferLength = sizeof( AFSFileCreateResultCB);
1394
1395         pResultCB = (AFSFileCreateResultCB *)(*ResultCB)->ResultData;
1396
1397         dwRemaining = ResultBufferLength - sizeof( AFSFileCreateResultCB) + sizeof( AFSDirEnumEntry);
1398
1399         lock_ObtainWrite(&dscp->rw);
1400         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1401                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1402         if (code) {
1403             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1404             (*ResultCB)->ResultStatus = status;
1405             lock_ReleaseWrite(&dscp->rw);
1406             cm_ReleaseSCache(dscp);
1407             cm_ReleaseSCache(scp);
1408             osi_Log3(afsd_logp, "RDR_CreateFileEntry cm_SyncOp failure (2) dscp=0x%p code=0x%x status=0x%x",
1409                       dscp, code, status);
1410             return;
1411         }
1412
1413         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1414
1415         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1416         lock_ReleaseWrite(&dscp->rw);
1417
1418         if (cm_shortNames) {
1419             dfid.vnode = htonl(scp->fid.vnode);
1420             dfid.unique = htonl(scp->fid.unique);
1421
1422             if (!cm_Is8Dot3(FileName))
1423                 cm_Gen8Dot3NameIntW(FileName, &dfid, shortName, NULL);
1424             else
1425                 shortName[0] = '\0';
1426         }
1427
1428         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1429                                         dscp, scp, userp, &req, FileName, shortName,
1430                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1431                                         0, NULL, &dwRemaining);
1432
1433         if (bHoldFid)
1434             RDR_FlagScpInUse( scp, FALSE );
1435         cm_ReleaseSCache(scp);
1436         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1437         osi_Log0(afsd_logp, "RDR_CreateFileEntry SUCCESS");
1438     } else {
1439         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1440         (*ResultCB)->ResultStatus = status;
1441         (*ResultCB)->ResultBufferLength = 0;
1442         osi_Log2(afsd_logp, "RDR_CreateFileEntry FAILURE code=0x%x status=0x%x",
1443                   code, status);
1444     }
1445
1446     cm_ReleaseSCache(dscp);
1447
1448     return;
1449 }
1450
1451 void
1452 RDR_UpdateFileEntry( IN cm_user_t *userp,
1453                      IN AFSFileID FileId,
1454                      IN AFSFileUpdateCB *UpdateCB,
1455                      IN BOOL bWow64,
1456                      IN DWORD ResultBufferLength,
1457                      IN OUT AFSCommResult **ResultCB)
1458 {
1459     AFSFileUpdateResultCB *pResultCB = NULL;
1460     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1461     cm_fid_t            Fid;
1462     cm_fid_t            parentFid;
1463     afs_uint32          code;
1464     afs_uint32          flags = 0;
1465     cm_attr_t           setAttr;
1466     cm_scache_t *       scp = NULL;
1467     cm_scache_t *       dscp = NULL;
1468     cm_req_t            req;
1469     time_t              clientModTime;
1470     FILETIME            ft;
1471     DWORD               status;
1472     BOOL                bScpLocked = FALSE;
1473
1474     RDR_InitReq(&req, bWow64);
1475     memset(&setAttr, 0, sizeof(cm_attr_t));
1476
1477     osi_Log4(afsd_logp, "RDR_UpdateFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1478               UpdateCB->ParentId.Cell, UpdateCB->ParentId.Volume,
1479               UpdateCB->ParentId.Vnode, UpdateCB->ParentId.Unique);
1480     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1481               FileId.Cell, FileId.Volume,
1482               FileId.Vnode, FileId.Unique);
1483
1484     *ResultCB = (AFSCommResult *)malloc( size);
1485     if (!(*ResultCB)) {
1486         osi_Log0(afsd_logp, "RDR_UpdateFileEntry Out of Memory");
1487         return;
1488     }
1489
1490     memset( *ResultCB,
1491             '\0',
1492             size);
1493
1494     parentFid.cell   = UpdateCB->ParentId.Cell;
1495     parentFid.volume = UpdateCB->ParentId.Volume;
1496     parentFid.vnode  = UpdateCB->ParentId.Vnode;
1497     parentFid.unique = UpdateCB->ParentId.Unique;
1498     parentFid.hash   = UpdateCB->ParentId.Hash;
1499
1500     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1501     if (code) {
1502         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1503         (*ResultCB)->ResultStatus = status;
1504         if ( status == STATUS_INVALID_HANDLE)
1505             status = STATUS_OBJECT_PATH_INVALID;
1506         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1507                   code, status);
1508         return;
1509     }
1510
1511     lock_ObtainWrite(&dscp->rw);
1512     bScpLocked = TRUE;
1513     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1514                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1515     if (code) {
1516         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1517         (*ResultCB)->ResultStatus = status;
1518         lock_ReleaseWrite(&dscp->rw);
1519         cm_ReleaseSCache(dscp);
1520         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
1521                  dscp, code, status);
1522         return;
1523     }
1524
1525     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1526     lock_ReleaseWrite(&dscp->rw);
1527     bScpLocked = FALSE;
1528
1529     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1530         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1531         cm_ReleaseSCache(dscp);
1532         osi_Log1(afsd_logp, "RDR_UpdateFileEntry Not a Directory dscp=0x%p",
1533                  dscp);
1534         return;
1535     }
1536
1537     Fid.cell   = FileId.Cell;
1538     Fid.volume = FileId.Volume;
1539     Fid.vnode  = FileId.Vnode;
1540     Fid.unique = FileId.Unique;
1541     Fid.hash   = FileId.Hash;
1542
1543     code = cm_GetSCache(&Fid, &dscp->fid, &scp, userp, &req);
1544     if (code) {
1545         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1546         (*ResultCB)->ResultStatus = status;
1547         cm_ReleaseSCache(dscp);
1548         osi_Log2(afsd_logp, "RDR_UpdateFileEntry cm_GetSCache object FID failure code=0x%x status=0x%x",
1549                   code, status);
1550         return;
1551     }
1552
1553     lock_ObtainWrite(&scp->rw);
1554     bScpLocked = TRUE;
1555     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1556                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1557     if (code) {
1558         lock_ReleaseWrite(&scp->rw);
1559         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1560         (*ResultCB)->ResultStatus = status;
1561         (*ResultCB)->ResultBufferLength = 0;
1562         cm_ReleaseSCache(dscp);
1563         cm_ReleaseSCache(scp);
1564         osi_Log3(afsd_logp, "RDR_UpdateFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
1565                  scp, code, status);
1566         return;
1567     }
1568     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1569
1570     if (UpdateCB->ChangeTime.QuadPart) {
1571
1572         if (scp->fileType == CM_SCACHETYPE_FILE) {
1573             /* Do not set length and other attributes at the same time */
1574             if (scp->length.QuadPart != UpdateCB->AllocationSize.QuadPart) {
1575                 osi_Log2(afsd_logp, "RDR_UpdateFileEntry Length Change 0x%x -> 0x%x",
1576                           (afs_uint32)scp->length.QuadPart, (afs_uint32)UpdateCB->AllocationSize.QuadPart);
1577                 setAttr.mask |= CM_ATTRMASK_LENGTH;
1578                 setAttr.length.LowPart = UpdateCB->AllocationSize.LowPart;
1579                 setAttr.length.HighPart = UpdateCB->AllocationSize.HighPart;
1580                 lock_ReleaseWrite(&scp->rw);
1581                 bScpLocked = FALSE;
1582                 code = cm_SetAttr(scp, &setAttr, userp, &req);
1583                 if (code)
1584                     goto on_error;
1585                 setAttr.mask = 0;
1586             }
1587         }
1588
1589         if (!bScpLocked) {
1590             lock_ObtainWrite(&scp->rw);
1591             bScpLocked = TRUE;
1592         }
1593         if ((scp->unixModeBits & 0200) && (UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1594             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1595             setAttr.unixModeBits = scp->unixModeBits & ~0222;
1596         } else if (!(scp->unixModeBits & 0200) && !(UpdateCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1597             setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1598             setAttr.unixModeBits = scp->unixModeBits | 0222;
1599         }
1600     }
1601
1602     if (UpdateCB->LastWriteTime.QuadPart) {
1603         ft.dwLowDateTime = UpdateCB->LastWriteTime.LowPart;
1604         ft.dwHighDateTime = UpdateCB->LastWriteTime.HighPart;
1605
1606         cm_UnixTimeFromLargeSearchTime(& clientModTime, &ft);
1607
1608         if (!bScpLocked) {
1609             lock_ObtainWrite(&scp->rw);
1610             bScpLocked = TRUE;
1611         }
1612         if (scp->clientModTime != clientModTime) {
1613             setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1614             setAttr.clientModTime = clientModTime;
1615         }
1616
1617         /* call setattr */
1618         if (setAttr.mask) {
1619             lock_ReleaseWrite(&scp->rw);
1620             bScpLocked = FALSE;
1621             code = cm_SetAttr(scp, &setAttr, userp, &req);
1622         } else
1623             code = 0;
1624     }
1625
1626   on_error:
1627     if (bScpLocked) {
1628         lock_ReleaseWrite(&scp->rw);
1629     }
1630
1631     if (code == 0) {
1632         DWORD dwRemaining = ResultBufferLength - sizeof( AFSFileUpdateResultCB) + sizeof( AFSDirEnumEntry);
1633
1634         pResultCB = (AFSFileUpdateResultCB *)(*ResultCB)->ResultData;
1635
1636         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
1637
1638         code = RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
1639                                         dscp, scp, userp, &req, NULL, NULL,
1640                                         RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
1641                                         0, NULL, &dwRemaining);
1642         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
1643         osi_Log0(afsd_logp, "RDR_UpdateFileEntry SUCCESS");
1644     } else {
1645         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1646         (*ResultCB)->ResultStatus = status;
1647         (*ResultCB)->ResultBufferLength = 0;
1648         osi_Log2(afsd_logp, "RDR_UpdateFileEntry FAILURE code=0x%x status=0x%x",
1649                   code, status);
1650     }
1651     cm_ReleaseSCache(scp);
1652     cm_ReleaseSCache(dscp);
1653
1654     return;
1655 }
1656
1657 void
1658 RDR_CleanupFileEntry( IN cm_user_t *userp,
1659                       IN AFSFileID FileId,
1660                       IN WCHAR *FileNameCounted,
1661                       IN DWORD FileNameLength,
1662                       IN AFSFileCleanupCB *CleanupCB,
1663                       IN BOOL bWow64,
1664                       IN BOOL bLastHandle,
1665                       IN BOOL bDeleteFile,
1666                       IN BOOL bUnlockFile,
1667                       IN DWORD ResultBufferLength,
1668                       IN OUT AFSCommResult **ResultCB)
1669 {
1670     AFSFileCleanupResultCB *pResultCB = NULL;
1671     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
1672     cm_fid_t            Fid;
1673     cm_fid_t            parentFid;
1674     afs_uint32          code = 0;
1675     afs_uint32          flags = 0;
1676     cm_attr_t           setAttr;
1677     cm_scache_t *       scp = NULL;
1678     cm_scache_t *       dscp = NULL;
1679     cm_req_t            req;
1680     time_t              clientModTime;
1681     FILETIME            ft;
1682     DWORD               status;
1683     BOOL                bScpLocked = FALSE;
1684     BOOL                bDscpLocked = FALSE;
1685     BOOL                bFlushFile = FALSE;
1686     cm_key_t            key;
1687
1688     RDR_InitReq(&req, bWow64);
1689     memset(&setAttr, 0, sizeof(cm_attr_t));
1690
1691     osi_Log4(afsd_logp, "RDR_CleanupFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1692               CleanupCB->ParentId.Cell, CleanupCB->ParentId.Volume,
1693               CleanupCB->ParentId.Vnode, CleanupCB->ParentId.Unique);
1694     osi_Log4(afsd_logp, "... object FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
1695               FileId.Cell, FileId.Volume,
1696               FileId.Vnode, FileId.Unique);
1697
1698     *ResultCB = (AFSCommResult *)malloc( size);
1699     if (!(*ResultCB)) {
1700         osi_Log0(afsd_logp, "RDR_CleanupFileEntry Out of Memory");
1701         return;
1702     }
1703
1704     memset( *ResultCB,
1705             '\0',
1706             size);
1707
1708     parentFid.cell   = CleanupCB->ParentId.Cell;
1709     parentFid.volume = CleanupCB->ParentId.Volume;
1710     parentFid.vnode  = CleanupCB->ParentId.Vnode;
1711     parentFid.unique = CleanupCB->ParentId.Unique;
1712     parentFid.hash   = CleanupCB->ParentId.Hash;
1713
1714     if (parentFid.cell) {
1715         code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
1716         if (code) {
1717             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
1718             if ( status == STATUS_INVALID_HANDLE)
1719                 status = STATUS_OBJECT_PATH_INVALID;
1720             (*ResultCB)->ResultStatus = status;
1721             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
1722                      code, status);
1723             return;
1724         }
1725
1726         lock_ObtainWrite(&dscp->rw);
1727         bDscpLocked = TRUE;
1728         code = cm_SyncOp(dscp, NULL, userp, &req, 0,
1729                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1730         if (code) {
1731             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure dscp=0x%p code=0x%x",
1732                     dscp, code);
1733             if (code)
1734                 goto on_error;
1735         }
1736
1737         cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1738         lock_ReleaseWrite(&dscp->rw);
1739         bDscpLocked = FALSE;
1740
1741         if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
1742             (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
1743             cm_ReleaseSCache(dscp);
1744             osi_Log1(afsd_logp, "RDR_CleanupFileEntry Not a Directory dscp=0x%p",
1745                      dscp);
1746             if (code)
1747                 goto on_error;
1748         }
1749     }
1750
1751     Fid.cell   = FileId.Cell;
1752     Fid.volume = FileId.Volume;
1753     Fid.vnode  = FileId.Vnode;
1754     Fid.unique = FileId.Unique;
1755     Fid.hash   = FileId.Hash;
1756
1757     code = cm_GetSCache(&Fid, dscp ? &dscp->fid : NULL, &scp, userp, &req);
1758     if (code) {
1759         osi_Log1(afsd_logp, "RDR_CleanupFileEntry cm_GetSCache object FID failure code=0x%x",
1760                  code);
1761         goto on_error;
1762     }
1763
1764     lock_ObtainWrite(&scp->rw);
1765     bScpLocked = TRUE;
1766     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1767                       CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_NEEDCALLBACK);
1768     if (code) {
1769         osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp failure scp=0x%p code=0x%x",
1770                  scp, code);
1771         goto on_error;
1772     }
1773     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1774
1775     if ((bLastHandle || bFlushFile) &&
1776         scp->redirBufCount > 0)
1777     {
1778         LARGE_INTEGER heldExtents;
1779         AFSFileExtentCB extentList[1024];
1780         DWORD extentCount = 0;
1781         cm_buf_t *srbp;
1782         time_t now;
1783
1784         time(&now);
1785         heldExtents.QuadPart = 0;
1786
1787         for ( srbp = redirq_to_cm_buf_t(scp->redirQueueT);
1788               srbp;
1789               srbp = redirq_to_cm_buf_t(osi_QPrev(&srbp->redirq)))
1790         {
1791             extentList[extentCount].Flags = 0;
1792             extentList[extentCount].Length = cm_data.blockSize;
1793             extentList[extentCount].FileOffset.QuadPart = srbp->offset.QuadPart;
1794             extentList[extentCount].CacheOffset.QuadPart = srbp->datap - RDR_extentBaseAddress;
1795             lock_ObtainWrite(&buf_globalLock);
1796             srbp->redirReleaseRequested = now;
1797             lock_ReleaseWrite(&buf_globalLock);
1798             extentCount++;
1799
1800             if (extentCount == 1024) {
1801                 lock_ReleaseWrite(&scp->rw);
1802                 code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1803                 if (code) {
1804                     if (code == CM_ERROR_RETRY) {
1805                         /*
1806                          * The redirector either is not holding the extents or cannot let them
1807                          * go because they are otherwise in use.  At the moment, do nothing.
1808                          */
1809                     } else
1810                         break;
1811                 }
1812                 extentCount = 0;
1813                 bFlushFile = TRUE;
1814                 lock_ObtainWrite(&scp->rw);
1815             }
1816         }
1817
1818         if (code == 0 && extentCount > 0) {
1819             if (bScpLocked) {
1820                 lock_ReleaseWrite(&scp->rw);
1821                 bScpLocked = FALSE;
1822             }
1823             code = RDR_RequestExtentRelease(&scp->fid, heldExtents, extentCount, extentList);
1824             bFlushFile = TRUE;
1825         }
1826     }
1827
1828     /* No longer in use by redirector */
1829     if (!bScpLocked) {
1830         lock_ObtainWrite(&scp->rw);
1831         bScpLocked = TRUE;
1832     }
1833
1834     if (bLastHandle) {
1835         lock_AssertWrite(&scp->rw);
1836         scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
1837     }
1838
1839     /* If not a readonly object, flush dirty data and update metadata */
1840     if (!(scp->flags & CM_SCACHEFLAG_RO)) {
1841         if ((bLastHandle || bFlushFile) &&
1842              buf_DirtyBuffersExist(&scp->fid)) {
1843             if (!bScpLocked) {
1844                 lock_ObtainWrite(&scp->rw);
1845                 bScpLocked = TRUE;
1846             }
1847             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
1848                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1849             if (code == 0) {
1850                 if (bScpLocked) {
1851                     lock_ReleaseWrite(&scp->rw);
1852                     bScpLocked = FALSE;
1853                 }
1854
1855                 code = cm_FSync(scp, userp, &req, bScpLocked);
1856             }
1857             if (bLastHandle && code)
1858                 goto unlock;
1859         }
1860
1861         if (CleanupCB->ChangeTime.QuadPart) {
1862
1863             if (scp->fileType == CM_SCACHETYPE_FILE) {
1864                 /* Do not set length and other attributes at the same time */
1865                 if (scp->length.QuadPart != CleanupCB->AllocationSize.QuadPart) {
1866                     osi_Log2(afsd_logp, "RDR_CleanupFileEntry Length Change 0x%x -> 0x%x",
1867                              (afs_uint32)scp->length.QuadPart, (afs_uint32)CleanupCB->AllocationSize.QuadPart);
1868                     setAttr.mask |= CM_ATTRMASK_LENGTH;
1869                     setAttr.length.LowPart = CleanupCB->AllocationSize.LowPart;
1870                     setAttr.length.HighPart = CleanupCB->AllocationSize.HighPart;
1871
1872                     if (bScpLocked) {
1873                         lock_ReleaseWrite(&scp->rw);
1874                         bScpLocked = FALSE;
1875                     }
1876                     code = cm_SetAttr(scp, &setAttr, userp, &req);
1877                     if (code)
1878                         goto unlock;
1879                     setAttr.mask = 0;
1880                 }
1881             }
1882
1883             if (!bScpLocked) {
1884                 lock_ObtainWrite(&scp->rw);
1885                 bScpLocked = TRUE;
1886             }
1887
1888             if ((scp->unixModeBits & 0200) && (CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1889                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1890                 setAttr.unixModeBits = scp->unixModeBits & ~0222;
1891             } else if (!(scp->unixModeBits & 0200) && !(CleanupCB->FileAttributes & FILE_ATTRIBUTE_READONLY)) {
1892                 setAttr.mask |= CM_ATTRMASK_UNIXMODEBITS;
1893                 setAttr.unixModeBits = scp->unixModeBits | 0222;
1894             }
1895         }
1896
1897         if (CleanupCB->LastWriteTime.QuadPart) {
1898             ft.dwLowDateTime = CleanupCB->LastWriteTime.LowPart;
1899             ft.dwHighDateTime = CleanupCB->LastWriteTime.HighPart;
1900
1901             cm_UnixTimeFromLargeSearchTime(&clientModTime, &ft);
1902             if (scp->clientModTime != clientModTime) {
1903                 setAttr.mask |= CM_ATTRMASK_CLIENTMODTIME;
1904                 setAttr.clientModTime = clientModTime;
1905             }
1906         }
1907
1908         /* call setattr */
1909         if (setAttr.mask) {
1910             if (bScpLocked) {
1911                 lock_ReleaseWrite(&scp->rw);
1912                 bScpLocked = FALSE;
1913             }
1914             code = cm_SetAttr(scp, &setAttr, userp, &req);
1915         } else
1916             code = 0;
1917     }
1918
1919   unlock:
1920     /* Now drop the lock enforcing the share access */
1921     if ( CleanupCB->FileAccess != AFS_FILE_ACCESS_NOLOCK) {
1922         unsigned int sLockType;
1923         LARGE_INTEGER LOffset, LLength;
1924
1925         if (CleanupCB->FileAccess == AFS_FILE_ACCESS_SHARED)
1926             sLockType = LOCKING_ANDX_SHARED_LOCK;
1927         else
1928             sLockType = 0;
1929
1930         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, CleanupCB->Identifier);
1931
1932         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
1933         LOffset.LowPart = SMB_FID_QLOCK_LOW;
1934         LLength.HighPart = 0;
1935         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
1936
1937         if (!bScpLocked) {
1938             lock_ObtainWrite(&scp->rw);
1939             bScpLocked = TRUE;
1940         }
1941
1942         code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
1943         if (code == 0)
1944         {
1945             code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
1946
1947             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
1948
1949             if (code == CM_ERROR_RANGE_NOT_LOCKED)
1950             {
1951                 osi_Log3(afsd_logp, "RDR_CleanupFileEntry Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
1952                          CleanupCB->FileAccess, CleanupCB->ProcessId, CleanupCB->Identifier);
1953
1954             }
1955         }
1956     }
1957
1958     if (bUnlockFile || bDeleteFile) {
1959         if (!bScpLocked) {
1960             lock_ObtainWrite(&scp->rw);
1961             bScpLocked = TRUE;
1962         }
1963         code = cm_SyncOp(scp, NULL, userp, &req, 0,
1964                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1965         if (code) {
1966             osi_Log2(afsd_logp, "RDR_CleanupFileEntry cm_SyncOp (2) failure scp=0x%p code=0x%x",
1967                      scp, code);
1968             goto on_error;
1969         }
1970
1971         key = cm_GenerateKey(CM_SESSION_IFS, CleanupCB->ProcessId, 0);
1972
1973         /* the scp is now locked and current */
1974         code = cm_UnlockByKey(scp, key,
1975                               bDeleteFile ? CM_UNLOCK_FLAG_BY_FID : 0,
1976                               userp, &req);
1977
1978         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
1979
1980         if (code)
1981             goto on_error;
1982     }
1983
1984   on_error:
1985     if (bDscpLocked)
1986         lock_ReleaseWrite(&dscp->rw);
1987     if (bScpLocked)
1988         lock_ReleaseWrite(&scp->rw);
1989
1990     if (code == 0 && dscp && bDeleteFile) {
1991         WCHAR FileName[260];
1992
1993         StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
1994
1995         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
1996             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
1997         else
1998             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
1999     }
2000
2001     if (code == 0) {
2002         if ( ResultBufferLength >=  sizeof( AFSFileCleanupResultCB))
2003         {
2004             (*ResultCB)->ResultBufferLength = sizeof( AFSFileCleanupResultCB);
2005             pResultCB = (AFSFileCleanupResultCB *)&(*ResultCB)->ResultData;
2006             pResultCB->ParentDataVersion.QuadPart = dscp ? dscp->dataVersion : 0;
2007         } else {
2008             (*ResultCB)->ResultBufferLength = 0;
2009         }
2010
2011         (*ResultCB)->ResultStatus = 0;
2012         osi_Log0(afsd_logp, "RDR_CleanupFileEntry SUCCESS");
2013     } else {
2014         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2015         (*ResultCB)->ResultStatus = status;
2016         osi_Log2(afsd_logp, "RDR_CleanupFileEntry FAILURE code=0x%x status=0x%x",
2017                   code, status);
2018     }
2019
2020     if (scp)
2021         cm_ReleaseSCache(scp);
2022     if (dscp)
2023         cm_ReleaseSCache(dscp);
2024
2025     return;
2026 }
2027
2028 void
2029 RDR_DeleteFileEntry( IN cm_user_t *userp,
2030                      IN AFSFileID ParentId,
2031                      IN ULONGLONG ProcessId,
2032                      IN WCHAR *FileNameCounted,
2033                      IN DWORD FileNameLength,
2034                      IN BOOL bWow64,
2035                      IN BOOL bCheckOnly,
2036                      IN DWORD ResultBufferLength,
2037                      IN OUT AFSCommResult **ResultCB)
2038 {
2039
2040     AFSFileDeleteResultCB *pResultCB = NULL;
2041     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2042     cm_fid_t            parentFid;
2043     afs_uint32          code;
2044     cm_scache_t *       dscp = NULL;
2045     cm_scache_t *       scp = NULL;
2046     afs_uint32          flags = 0;
2047     cm_attr_t           setAttr;
2048     cm_req_t            req;
2049     DWORD               status;
2050     wchar_t             FileName[260];
2051     cm_key_t            key;
2052
2053     StringCchCopyNW(FileName, 260, FileNameCounted, FileNameLength / sizeof(WCHAR));
2054
2055     osi_Log4(afsd_logp, "RDR_DeleteFileEntry parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2056               ParentId.Cell,  ParentId.Volume,
2057               ParentId.Vnode, ParentId.Unique);
2058     osi_Log2(afsd_logp, "... name=%S checkOnly=%x",
2059              osi_LogSaveStringW(afsd_logp, FileName),
2060              bCheckOnly);
2061
2062     RDR_InitReq(&req, bWow64);
2063     memset(&setAttr, 0, sizeof(cm_attr_t));
2064
2065     *ResultCB = (AFSCommResult *)malloc( size);
2066     if (!(*ResultCB)) {
2067         osi_Log0(afsd_logp, "RDR_DeleteFileEntry out of memory");
2068         return;
2069     }
2070
2071     memset( *ResultCB,
2072             '\0',
2073             size);
2074
2075     parentFid.cell   = ParentId.Cell;
2076     parentFid.volume = ParentId.Volume;
2077     parentFid.vnode  = ParentId.Vnode;
2078     parentFid.unique = ParentId.Unique;
2079     parentFid.hash   = ParentId.Hash;
2080
2081     code = cm_GetSCache(&parentFid, NULL, &dscp, userp, &req);
2082     if (code) {
2083         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2084         if ( status == STATUS_INVALID_HANDLE)
2085             status = STATUS_OBJECT_PATH_INVALID;
2086         (*ResultCB)->ResultStatus = status;
2087         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_GetSCache ParentFID failure code=0x%x status=0x%x",
2088                   code, status);
2089         return;
2090     }
2091
2092     lock_ObtainWrite(&dscp->rw);
2093
2094     code = cm_SyncOp(dscp, NULL, userp, &req, 0,
2095                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2096     if (code) {
2097         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2098         (*ResultCB)->ResultStatus = status;
2099         (*ResultCB)->ResultBufferLength = 0;
2100         lock_ReleaseWrite(&dscp->rw);
2101         cm_ReleaseSCache(dscp);
2102         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure dscp=0x%p code=0x%x status=0x%x",
2103                  dscp, code, status);
2104         return;
2105     }
2106
2107     cm_SyncOpDone(dscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2108     lock_ReleaseWrite(&dscp->rw);
2109
2110     if (dscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2111         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2112         cm_ReleaseSCache(dscp);
2113         osi_Log1(afsd_logp, "RDR_DeleteFileEntry Not a Directory dscp=0x%p",
2114                  dscp);
2115         return;
2116     }
2117
2118     code = cm_Lookup(dscp, FileName, 0, userp, &req, &scp);
2119     if (code) {
2120         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2121         (*ResultCB)->ResultStatus = status;
2122         (*ResultCB)->ResultBufferLength = 0;
2123         cm_ReleaseSCache(dscp);
2124         osi_Log2(afsd_logp, "RDR_DeleteFileEntry cm_Lookup failure code=0x%x status=0x%x",
2125                  code, status);
2126         return;
2127     }
2128
2129     lock_ObtainWrite(&scp->rw);
2130     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_DELETE,
2131                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2132     if (code) {
2133         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2134         (*ResultCB)->ResultStatus = status;
2135         (*ResultCB)->ResultBufferLength = 0;
2136         lock_ReleaseWrite(&scp->rw);
2137         cm_ReleaseSCache(scp);
2138         cm_ReleaseSCache(dscp);
2139         osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2140                  scp, code, status);
2141         return;
2142     }
2143
2144     if (!bCheckOnly) {
2145         /* Drop all locks since the file is being deleted */
2146         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2147                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2148         if (code) {
2149             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2150             (*ResultCB)->ResultStatus = status;
2151             (*ResultCB)->ResultBufferLength = 0;
2152             lock_ReleaseWrite(&scp->rw);
2153             cm_ReleaseSCache(scp);
2154             cm_ReleaseSCache(dscp);
2155             osi_Log3(afsd_logp, "RDR_DeleteFileEntry cm_SyncOp Lock failure scp=0x%p code=0x%x status=0x%x",
2156                      scp, code, status);
2157         }
2158
2159         /* the scp is now locked and current */
2160         key = cm_GenerateKey(CM_SESSION_IFS, ProcessId, 0);
2161
2162         code = cm_UnlockByKey(scp, key,
2163                               CM_UNLOCK_FLAG_BY_FID,
2164                               userp, &req);
2165
2166         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
2167         lock_ReleaseWrite(&scp->rw);
2168
2169         if (scp->fileType == CM_SCACHETYPE_DIRECTORY)
2170             code = cm_RemoveDir(dscp, NULL, FileName, userp, &req);
2171         else
2172             code = cm_Unlink(dscp, NULL, FileName, userp, &req);
2173     } else {
2174         lock_ReleaseWrite(&scp->rw);
2175     }
2176
2177     if (code == 0) {
2178         (*ResultCB)->ResultStatus = 0;  // We will be able to fit all the data in here
2179
2180         (*ResultCB)->ResultBufferLength = sizeof( AFSFileDeleteResultCB);
2181
2182         pResultCB = (AFSFileDeleteResultCB *)(*ResultCB)->ResultData;
2183
2184         pResultCB->ParentDataVersion.QuadPart = dscp->dataVersion;
2185         osi_Log0(afsd_logp, "RDR_DeleteFileEntry SUCCESS");
2186     } else {
2187         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2188         (*ResultCB)->ResultStatus = status;
2189         (*ResultCB)->ResultBufferLength = 0;
2190         osi_Log2(afsd_logp, "RDR_DeleteFileEntry FAILURE code=0x%x status=0x%x",
2191                   code, status);
2192     }
2193
2194     cm_ReleaseSCache(dscp);
2195     cm_ReleaseSCache(scp);
2196
2197     return;
2198 }
2199
2200 void
2201 RDR_RenameFileEntry( IN cm_user_t *userp,
2202                      IN WCHAR    *SourceFileNameCounted,
2203                      IN DWORD     SourceFileNameLength,
2204                      IN AFSFileID SourceFileId,
2205                      IN AFSFileRenameCB *pRenameCB,
2206                      IN BOOL bWow64,
2207                      IN DWORD ResultBufferLength,
2208                      IN OUT AFSCommResult **ResultCB)
2209 {
2210
2211     AFSFileRenameResultCB *pResultCB = NULL;
2212     size_t size = sizeof(AFSCommResult) + ResultBufferLength - 1;
2213     AFSFileID              SourceParentId   = pRenameCB->SourceParentId;
2214     AFSFileID              TargetParentId   = pRenameCB->TargetParentId;
2215     WCHAR *                TargetFileNameCounted = pRenameCB->TargetName;
2216     DWORD                  TargetFileNameLength = pRenameCB->TargetNameLength;
2217     cm_fid_t               SourceParentFid;
2218     cm_fid_t               TargetParentFid;
2219     cm_fid_t               SourceFid;
2220     cm_fid_t               OrigTargetFid = {0,0,0,0,0};
2221     cm_fid_t               TargetFid;
2222     cm_scache_t *          oldDscp;
2223     cm_scache_t *          newDscp;
2224     cm_dirOp_t dirop;
2225     wchar_t                shortName[13];
2226     wchar_t                SourceFileName[260];
2227     wchar_t                TargetFileName[260];
2228     cm_dirFid_t            dfid;
2229     cm_req_t               req;
2230     afs_uint32             code;
2231     DWORD                  status;
2232
2233     RDR_InitReq(&req, bWow64);
2234
2235     StringCchCopyNW(SourceFileName, 260, SourceFileNameCounted, SourceFileNameLength / sizeof(WCHAR));
2236     StringCchCopyNW(TargetFileName, 260, TargetFileNameCounted, TargetFileNameLength / sizeof(WCHAR));
2237
2238     osi_Log4(afsd_logp, "RDR_RenameFileEntry Source Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2239               SourceParentId.Cell,  SourceParentId.Volume,
2240               SourceParentId.Vnode, SourceParentId.Unique);
2241     osi_Log2(afsd_logp, "... Source Name=%S Length %u", osi_LogSaveStringW(afsd_logp, SourceFileName), SourceFileNameLength);
2242     osi_Log4(afsd_logp, "... Target Parent FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2243               TargetParentId.Cell,  TargetParentId.Volume,
2244               TargetParentId.Vnode, TargetParentId.Unique);
2245     osi_Log2(afsd_logp, "... Target Name=%S Length %u", osi_LogSaveStringW(afsd_logp, TargetFileName), TargetFileNameLength);
2246
2247     *ResultCB = (AFSCommResult *)malloc( size);
2248     if (!(*ResultCB))
2249         return;
2250
2251     memset( *ResultCB,
2252             '\0',
2253             size);
2254
2255     pResultCB = (AFSFileRenameResultCB *)(*ResultCB)->ResultData;
2256
2257     if (SourceFileNameLength == 0 || TargetFileNameLength == 0)
2258     {
2259         osi_Log2(afsd_logp, "RDR_RenameFileEntry Invalid Name Length: src %u target %u",
2260                  SourceFileNameLength, TargetFileNameLength);
2261         (*ResultCB)->ResultStatus = STATUS_INVALID_PARAMETER;
2262         return;
2263     }
2264
2265     SourceParentFid.cell   = SourceParentId.Cell;
2266     SourceParentFid.volume = SourceParentId.Volume;
2267     SourceParentFid.vnode  = SourceParentId.Vnode;
2268     SourceParentFid.unique = SourceParentId.Unique;
2269     SourceParentFid.hash   = SourceParentId.Hash;
2270
2271     TargetParentFid.cell   = TargetParentId.Cell;
2272     TargetParentFid.volume = TargetParentId.Volume;
2273     TargetParentFid.vnode  = TargetParentId.Vnode;
2274     TargetParentFid.unique = TargetParentId.Unique;
2275     TargetParentFid.hash   = TargetParentId.Hash;
2276
2277     code = cm_GetSCache(&SourceParentFid, NULL, &oldDscp, userp, &req);
2278     if (code) {
2279         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache source parent failed code 0x%x", code);
2280         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2281         if ( status == STATUS_INVALID_HANDLE)
2282             status = STATUS_OBJECT_PATH_INVALID;
2283         (*ResultCB)->ResultStatus = status;
2284         return;
2285     }
2286
2287     lock_ObtainWrite(&oldDscp->rw);
2288     code = cm_SyncOp(oldDscp, NULL, userp, &req, 0,
2289                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2290     if (code) {
2291         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp oldDscp 0x%p failed code 0x%x", oldDscp, code);
2292         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2293         if ( status == STATUS_INVALID_HANDLE)
2294             status = STATUS_OBJECT_PATH_INVALID;
2295         (*ResultCB)->ResultStatus = status;
2296         lock_ReleaseWrite(&oldDscp->rw);
2297         cm_ReleaseSCache(oldDscp);
2298         return;
2299     }
2300
2301     cm_SyncOpDone(oldDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2302     lock_ReleaseWrite(&oldDscp->rw);
2303
2304
2305     if (oldDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2306         osi_Log1(afsd_logp, "RDR_RenameFileEntry oldDscp 0x%p not a directory", oldDscp);
2307         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2308         cm_ReleaseSCache(oldDscp);
2309         return;
2310     }
2311
2312     code = cm_GetSCache(&TargetParentFid, NULL, &newDscp, userp, &req);
2313     if (code) {
2314         osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target parent failed code 0x%x", code);
2315         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2316         (*ResultCB)->ResultStatus = status;
2317         cm_ReleaseSCache(oldDscp);
2318         return;
2319     }
2320
2321     lock_ObtainWrite(&newDscp->rw);
2322     code = cm_SyncOp(newDscp, NULL, userp, &req, 0,
2323                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2324     if (code) {
2325         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp newDscp 0x%p failed code 0x%x", newDscp, code);
2326         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2327         (*ResultCB)->ResultStatus = status;
2328         lock_ReleaseWrite(&newDscp->rw);
2329         cm_ReleaseSCache(oldDscp);
2330         cm_ReleaseSCache(newDscp);
2331         return;
2332     }
2333
2334     cm_SyncOpDone(newDscp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2335     lock_ReleaseWrite(&newDscp->rw);
2336
2337
2338     if (newDscp->fileType != CM_SCACHETYPE_DIRECTORY) {
2339         osi_Log1(afsd_logp, "RDR_RenameFileEntry newDscp 0x%p not a directory", newDscp);
2340         (*ResultCB)->ResultStatus = STATUS_NOT_A_DIRECTORY;
2341         cm_ReleaseSCache(oldDscp);
2342         cm_ReleaseSCache(newDscp);
2343         return;
2344     }
2345
2346     /* Obtain the original FID just for debugging purposes */
2347     code = cm_BeginDirOp( oldDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2348     if (code == 0) {
2349         code = cm_BPlusDirLookup(&dirop, SourceFileName, &SourceFid);
2350         code = cm_BPlusDirLookup(&dirop, TargetFileName, &OrigTargetFid);
2351         cm_EndDirOp(&dirop);
2352     }
2353
2354     code = cm_Rename( oldDscp, NULL, SourceFileName,
2355                       newDscp, TargetFileName, userp, &req);
2356     if (code == 0) {
2357         cm_scache_t *scp = 0;
2358         DWORD dwRemaining;
2359
2360         (*ResultCB)->ResultBufferLength = ResultBufferLength;
2361         dwRemaining = ResultBufferLength - sizeof( AFSFileRenameResultCB) + sizeof( AFSDirEnumEntry);
2362         (*ResultCB)->ResultStatus = 0;
2363
2364         pResultCB->SourceParentDataVersion.QuadPart = oldDscp->dataVersion;
2365         pResultCB->TargetParentDataVersion.QuadPart = newDscp->dataVersion;
2366
2367         osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p SUCCESS",
2368                  oldDscp, newDscp);
2369
2370         code = cm_BeginDirOp( newDscp, userp, &req, CM_DIRLOCK_READ, CM_DIROP_FLAG_NONE, &dirop);
2371         if (code == 0) {
2372             code = cm_BPlusDirLookup(&dirop, TargetFileName, &TargetFid);
2373             cm_EndDirOp(&dirop);
2374         }
2375
2376         if (code != 0) {
2377             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_BPlusDirLookup failed code 0x%x",
2378                      code);
2379             (*ResultCB)->ResultStatus = STATUS_OBJECT_PATH_INVALID;
2380             cm_ReleaseSCache(oldDscp);
2381             cm_ReleaseSCache(newDscp);
2382             return;
2383         }
2384
2385         osi_Log4(afsd_logp, "RDR_RenameFileEntry Target FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2386                   TargetFid.cell,  TargetFid.volume,
2387                   TargetFid.vnode, TargetFid.unique);
2388
2389         code = cm_GetSCache(&TargetFid, &newDscp->fid, &scp, userp, &req);
2390         if (code) {
2391             osi_Log1(afsd_logp, "RDR_RenameFileEntry cm_GetSCache target failed code 0x%x", code);
2392             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2393             (*ResultCB)->ResultStatus = status;
2394             cm_ReleaseSCache(oldDscp);
2395             cm_ReleaseSCache(newDscp);
2396             return;
2397         }
2398
2399         /* Make sure the source vnode is current */
2400         lock_ObtainWrite(&scp->rw);
2401         code = cm_SyncOp(scp, NULL, userp, &req, 0,
2402                           CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2403         if (code) {
2404             osi_Log2(afsd_logp, "RDR_RenameFileEntry cm_SyncOp scp 0x%p failed code 0x%x", scp, code);
2405             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2406             (*ResultCB)->ResultStatus = status;
2407             lock_ReleaseWrite(&scp->rw);
2408             cm_ReleaseSCache(oldDscp);
2409             cm_ReleaseSCache(newDscp);
2410             cm_ReleaseSCache(scp);
2411             return;
2412         }
2413
2414         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2415         lock_ReleaseWrite(&scp->rw);
2416
2417         if (cm_shortNames) {
2418             dfid.vnode = htonl(scp->fid.vnode);
2419             dfid.unique = htonl(scp->fid.unique);
2420
2421             if (!cm_Is8Dot3(TargetFileName))
2422                 cm_Gen8Dot3NameIntW(TargetFileName, &dfid, shortName, NULL);
2423             else
2424                 shortName[0] = '\0';
2425         }
2426
2427         RDR_PopulateCurrentEntry(&pResultCB->DirEnum, dwRemaining,
2428                                  newDscp, scp, userp, &req, TargetFileName, shortName,
2429                                  RDR_POP_FOLLOW_MOUNTPOINTS | RDR_POP_EVALUATE_SYMLINKS,
2430                                  0, NULL, &dwRemaining);
2431         (*ResultCB)->ResultBufferLength = ResultBufferLength - dwRemaining;
2432         cm_ReleaseSCache(scp);
2433
2434         osi_Log0(afsd_logp, "RDR_RenameFileEntry SUCCESS");
2435     } else {
2436         osi_Log3(afsd_logp, "RDR_RenameFileEntry cm_Rename oldDscp 0x%p newDscp 0x%p failed code 0x%x",
2437                  oldDscp, newDscp, code);
2438         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2439         (*ResultCB)->ResultStatus = status;
2440         (*ResultCB)->ResultBufferLength = 0;
2441     }
2442
2443     cm_ReleaseSCache(oldDscp);
2444     cm_ReleaseSCache(newDscp);
2445     return;
2446 }
2447
2448 void
2449 RDR_FlushFileEntry( IN cm_user_t *userp,
2450                     IN AFSFileID FileId,
2451                     IN BOOL bWow64,
2452                     IN DWORD ResultBufferLength,
2453                     IN OUT AFSCommResult **ResultCB)
2454 {
2455     cm_scache_t *scp = NULL;
2456     cm_fid_t    Fid;
2457     afs_uint32  code;
2458     cm_req_t    req;
2459     DWORD       status;
2460 #ifdef ODS_DEBUG
2461     char        dbgstr[1024];
2462 #endif
2463
2464     RDR_InitReq(&req, bWow64);
2465
2466     osi_Log4(afsd_logp, "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x",
2467               FileId.Cell, FileId.Volume,
2468               FileId.Vnode, FileId.Unique);
2469 #ifdef ODS_DEBUG
2470     snprintf( dbgstr, 1024,
2471               "RDR_FlushFileEntry File FID cell 0x%x vol 0x%x vno 0x%x uniq 0x%x\n",
2472               FileId.Cell, FileId.Volume,
2473               FileId.Vnode, FileId.Unique);
2474     OutputDebugStringA( dbgstr);
2475 #endif
2476
2477     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2478     if (!(*ResultCB)) {
2479         osi_Log0(afsd_logp, "RDR_FlushFileEntry out of memory");
2480         return;
2481     }
2482
2483     memset( *ResultCB,
2484             '\0',
2485             sizeof( AFSCommResult));
2486
2487     /* Process the release */
2488     Fid.cell = FileId.Cell;
2489     Fid.volume = FileId.Volume;
2490     Fid.vnode = FileId.Vnode;
2491     Fid.unique = FileId.Unique;
2492     Fid.hash = FileId.Hash;
2493
2494     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2495     if (code) {
2496         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2497         (*ResultCB)->ResultStatus = status;
2498         osi_Log2(afsd_logp, "RDR_FlushFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2499                   code, status);
2500         return;
2501     }
2502
2503     lock_ObtainWrite(&scp->rw);
2504     if (scp->flags & CM_SCACHEFLAG_DELETED) {
2505         lock_ReleaseWrite(&scp->rw);
2506         (*ResultCB)->ResultStatus = STATUS_INVALID_HANDLE;
2507         return;
2508     }
2509
2510     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2511                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2512     if (code) {
2513         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2514         (*ResultCB)->ResultStatus = status;
2515         lock_ReleaseWrite(&scp->rw);
2516         cm_ReleaseSCache(scp);
2517         osi_Log3(afsd_logp, "RDR_FlushFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2518                  scp, code, status);
2519         return;
2520     }
2521
2522     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2523     lock_ReleaseWrite(&scp->rw);
2524
2525     code = cm_FSync(scp, userp, &req, FALSE);
2526     cm_ReleaseSCache(scp);
2527
2528     if (code) {
2529         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2530         (*ResultCB)->ResultStatus = status;
2531         osi_Log2(afsd_logp, "RDR_FlushFileEntry FAILURE code=0x%x status=0x%x",
2532                   code, status);
2533     } else {
2534         (*ResultCB)->ResultStatus = 0;
2535         osi_Log0(afsd_logp, "RDR_FlushFileEntry SUCCESS");
2536     }
2537     (*ResultCB)->ResultBufferLength = 0;
2538
2539     return;
2540 }
2541
2542 afs_uint32
2543 RDR_CheckAccess( IN cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp,
2544                  ULONG access,
2545                  ULONG *granted)
2546 {
2547     ULONG afs_acc, afs_gr;
2548     BOOLEAN file, dir;
2549     afs_uint32 code = 0;
2550
2551     file = (scp->fileType == CM_SCACHETYPE_FILE);
2552     dir = !file;
2553
2554     /* access definitions from prs_fs.h */
2555     afs_acc = 0;
2556     if (access & FILE_READ_DATA)
2557         afs_acc |= PRSFS_READ;
2558     if (access & FILE_READ_EA || access & FILE_READ_ATTRIBUTES)
2559         afs_acc |= PRSFS_READ;
2560     if (file && ((access & FILE_WRITE_DATA) || (access & FILE_APPEND_DATA)))
2561         afs_acc |= PRSFS_WRITE;
2562     if (access & FILE_WRITE_EA || access & FILE_WRITE_ATTRIBUTES)
2563         afs_acc |= PRSFS_WRITE;
2564     if (dir && ((access & FILE_ADD_FILE) || (access & FILE_ADD_SUBDIRECTORY)))
2565         afs_acc |= PRSFS_INSERT;
2566     if (dir && (access & FILE_LIST_DIRECTORY))
2567         afs_acc |= PRSFS_LOOKUP;
2568     if (file && (access & FILE_EXECUTE))
2569         afs_acc |= PRSFS_WRITE;
2570     if (dir && (access & FILE_TRAVERSE))
2571         afs_acc |= PRSFS_READ;
2572     if (dir && (access & FILE_DELETE_CHILD))
2573         afs_acc |= PRSFS_DELETE;
2574     if ((access & DELETE))
2575         afs_acc |= PRSFS_DELETE;
2576
2577     /* check ACL with server */
2578     lock_ObtainWrite(&scp->rw);
2579     while (1)
2580     {
2581         if (cm_HaveAccessRights(scp, userp, reqp, afs_acc, &afs_gr))
2582         {
2583             break;
2584         }
2585         else
2586         {
2587             /* we don't know the required access rights */
2588             code = cm_GetAccessRights(scp, userp, reqp);
2589             if (code)
2590                 break;
2591             continue;
2592         }
2593     }
2594     lock_ReleaseWrite(&(scp->rw));
2595
2596     if (code == 0) {
2597         *granted = 0;
2598         if (afs_gr & PRSFS_READ)
2599             *granted |= FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | FILE_EXECUTE;
2600         if (afs_gr & PRSFS_WRITE)
2601             *granted |= FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | FILE_EXECUTE;
2602         if (afs_gr & PRSFS_INSERT)
2603             *granted |= (dir ? FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY : 0) | (file ? FILE_ADD_SUBDIRECTORY : 0);
2604         if (afs_gr & PRSFS_LOOKUP)
2605             *granted |= (dir ? FILE_LIST_DIRECTORY : 0);
2606         if (afs_gr & PRSFS_DELETE)
2607             *granted |= FILE_DELETE_CHILD | DELETE;
2608         if (afs_gr & PRSFS_LOCK)
2609             *granted |= 0;
2610         if (afs_gr & PRSFS_ADMINISTER)
2611             *granted |= 0;
2612
2613         *granted |= SYNCHRONIZE | READ_CONTROL;
2614
2615         /* don't give more access than what was requested */
2616         *granted &= access;
2617         osi_Log3(afsd_logp, "RDR_CheckAccess SUCCESS scp=0x%p requested=0x%x granted=0x%x", scp, access, *granted);
2618     } else
2619         osi_Log2(afsd_logp, "RDR_CheckAccess FAILURE scp=0x%p code=0x%x",
2620                  scp, code);
2621
2622     return code;
2623 }
2624
2625 void
2626 RDR_OpenFileEntry( IN cm_user_t *userp,
2627                    IN AFSFileID FileId,
2628                    IN AFSFileOpenCB *OpenCB,
2629                    IN BOOL bWow64,
2630                    IN BOOL bHoldFid,
2631                    IN DWORD ResultBufferLength,
2632                    IN OUT AFSCommResult **ResultCB)
2633 {
2634     AFSFileOpenResultCB *pResultCB = NULL;
2635     cm_scache_t *scp = NULL;
2636     cm_user_t   *sysUserp = NULL;
2637     cm_fid_t    Fid;
2638     cm_lock_data_t      *ldp = NULL;
2639     afs_uint32  code;
2640     cm_req_t    req;
2641     DWORD       status;
2642
2643     RDR_InitReq(&req, bWow64);
2644
2645     osi_Log4(afsd_logp, "RDR_OpenFileEntry File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2646               FileId.Cell, FileId.Volume,
2647               FileId.Vnode, FileId.Unique);
2648
2649     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2650     if (!(*ResultCB)) {
2651         osi_Log0(afsd_logp, "RDR_OpenFileEntry out of memory");
2652         return;
2653     }
2654
2655     memset( *ResultCB,
2656             '\0',
2657             sizeof( AFSCommResult) + sizeof( AFSFileOpenResultCB));
2658
2659     pResultCB = (AFSFileOpenResultCB *)(*ResultCB)->ResultData;
2660
2661     /* Process the release */
2662     Fid.cell = FileId.Cell;
2663     Fid.volume = FileId.Volume;
2664     Fid.vnode = FileId.Vnode;
2665     Fid.unique = FileId.Unique;
2666     Fid.hash = FileId.Hash;
2667
2668     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2669     if (code) {
2670         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2671         (*ResultCB)->ResultStatus = status;
2672         osi_Log2(afsd_logp, "RDR_OpenFileEntry cm_GetSCache FID failure code=0x%x status=0x%x",
2673                   code, status);
2674         return;
2675     }
2676
2677     lock_ObtainWrite(&scp->rw);
2678     code = cm_SyncOp(scp, NULL, userp, &req, 0,
2679                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2680     if (code) {
2681         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2682         (*ResultCB)->ResultStatus = status;
2683         lock_ReleaseWrite(&scp->rw);
2684         cm_ReleaseSCache(scp);
2685         osi_Log3(afsd_logp, "RDR_OpenFileEntry cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
2686                  scp, code, status);
2687         return;
2688     }
2689
2690     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2691     lock_ReleaseWrite(&scp->rw);
2692
2693     sysUserp = RDR_GetLocalSystemUser();
2694
2695     /*
2696      * Skip the open check if the request is coming from the local system account.
2697      * The local system has no tokens and therefore any requests sent to a file
2698      * server will fail.  Unfortunately, there are special system processes that
2699      * perform actions on files and directories in preparation for memory mapping
2700      * executables.  If the open check fails, the real request from the user process
2701      * will never be issued.
2702      *
2703      * Permitting the file system to allow subsequent operations to proceed does
2704      * not compromise security.  All requests to obtain file data or directory
2705      * enumerations will subsequently fail if they are not submitted under the
2706      * context of a process for that have access to the necessary credentials.
2707      */
2708
2709     if ( userp == sysUserp)
2710     {
2711         osi_Log1(afsd_logp, "RDR_OpenFileEntry LOCAL_SYSTEM access check skipped scp=0x%p",
2712                  scp);
2713         pResultCB->GrantedAccess = OpenCB->DesiredAccess;
2714         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2715         code = 0;
2716     }
2717     else
2718     {
2719         int count = 0;
2720
2721         do {
2722             if (count++ > 0) {
2723                 Sleep(350);
2724                 osi_Log3(afsd_logp,
2725                          "RDR_OpenFileEntry repeating open check scp=0x%p userp=0x%p code=0x%x",
2726                          scp, userp, code);
2727             }
2728             code = cm_CheckNTOpen(scp, OpenCB->DesiredAccess, OpenCB->ShareAccess,
2729                                   OPEN_ALWAYS,
2730                                   OpenCB->ProcessId, OpenCB->Identifier,
2731                                   userp, &req, &ldp);
2732             if (code == 0)
2733                 code = RDR_CheckAccess(scp, userp, &req, OpenCB->DesiredAccess, &pResultCB->GrantedAccess);
2734             cm_CheckNTOpenDone(scp, userp, &req, &ldp);
2735         } while (count < 100 && (code == CM_ERROR_RETRY || code == CM_ERROR_WOULDBLOCK));
2736     }
2737
2738     /*
2739      * If we are restricting sharing, we should do so with a suitable
2740      * share lock.
2741      */
2742     if (code == 0 && scp->fileType == CM_SCACHETYPE_FILE && !(OpenCB->ShareAccess & FILE_SHARE_WRITE)) {
2743         cm_key_t key;
2744         LARGE_INTEGER LOffset, LLength;
2745         int sLockType;
2746
2747         LOffset.HighPart = SMB_FID_QLOCK_HIGH;
2748         LOffset.LowPart = SMB_FID_QLOCK_LOW;
2749         LLength.HighPart = 0;
2750         LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2751
2752         /*
2753          * If we are not opening the file for writing, then we don't
2754          * try to get an exclusive lock.  No one else should be able to
2755          * get an exclusive lock on the file anyway, although someone
2756          * else can get a shared lock.
2757          */
2758         if ((OpenCB->ShareAccess & FILE_SHARE_READ) || !(OpenCB->DesiredAccess & AFS_ACCESS_WRITE))
2759         {
2760             sLockType = LOCKING_ANDX_SHARED_LOCK;
2761         } else {
2762             sLockType = 0;
2763         }
2764
2765         key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, OpenCB->Identifier);
2766
2767         lock_ObtainWrite(&scp->rw);
2768         code = cm_Lock(scp, sLockType, LOffset, LLength, key, 0, userp, &req, NULL);
2769         lock_ReleaseWrite(&scp->rw);
2770
2771         if (code) {
2772             code = CM_ERROR_SHARING_VIOLATION;
2773             pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2774         } else {
2775             if (sLockType == LOCKING_ANDX_SHARED_LOCK)
2776                 pResultCB->FileAccess = AFS_FILE_ACCESS_SHARED;
2777             else
2778                 pResultCB->FileAccess = AFS_FILE_ACCESS_EXCLUSIVE;
2779         }
2780     } else {
2781         pResultCB->FileAccess = AFS_FILE_ACCESS_NOLOCK;
2782     }
2783
2784     cm_ReleaseUser(sysUserp);
2785     if (code == 0 && bHoldFid)
2786         RDR_FlagScpInUse( scp, FALSE );
2787     cm_ReleaseSCache(scp);
2788
2789     if (code) {
2790         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2791         (*ResultCB)->ResultStatus = status;
2792         osi_Log2(afsd_logp, "RDR_OpenFileEntry FAILURE code=0x%x status=0x%x",
2793                   code, status);
2794     } else {
2795         (*ResultCB)->ResultStatus = 0;
2796         (*ResultCB)->ResultBufferLength = sizeof( AFSFileOpenResultCB);
2797         osi_Log0(afsd_logp, "RDR_OpenFileEntry SUCCESS");
2798     }
2799     return;
2800 }
2801
2802 void
2803 RDR_ReleaseFileAccess( IN cm_user_t *userp,
2804                        IN AFSFileID FileId,
2805                        IN AFSFileAccessReleaseCB *ReleaseFileCB,
2806                        IN BOOL bWow64,
2807                        IN DWORD ResultBufferLength,
2808                        IN OUT AFSCommResult **ResultCB)
2809 {
2810     cm_key_t key;
2811     unsigned int sLockType;
2812     LARGE_INTEGER LOffset, LLength;
2813     cm_scache_t *scp = NULL;
2814     cm_fid_t    Fid;
2815     afs_uint32  code;
2816     cm_req_t    req;
2817     DWORD       status;
2818
2819     RDR_InitReq(&req, bWow64);
2820
2821     osi_Log4(afsd_logp, "RDR_ReleaseFileAccess File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
2822               FileId.Cell, FileId.Volume,
2823               FileId.Vnode, FileId.Unique);
2824
2825     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
2826     if (!(*ResultCB)) {
2827         osi_Log0(afsd_logp, "RDR_ReleaseFileAccess out of memory");
2828         return;
2829     }
2830
2831     memset( *ResultCB, '\0', sizeof( AFSCommResult));
2832
2833     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_NOLOCK)
2834         return;
2835
2836     /* Process the release */
2837     Fid.cell = FileId.Cell;
2838     Fid.volume = FileId.Volume;
2839     Fid.vnode = FileId.Vnode;
2840     Fid.unique = FileId.Unique;
2841     Fid.hash = FileId.Hash;
2842
2843     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
2844     if (code) {
2845         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
2846         (*ResultCB)->ResultStatus = status;
2847         osi_Log2(afsd_logp, "RDR_ReleaseFileAccess cm_GetSCache FID failure code=0x%x status=0x%x",
2848                   code, status);
2849         return;
2850     }
2851
2852     if (ReleaseFileCB->FileAccess == AFS_FILE_ACCESS_SHARED)
2853         sLockType = LOCKING_ANDX_SHARED_LOCK;
2854     else
2855         sLockType = 0;
2856
2857     key = cm_GenerateKey(CM_SESSION_IFS, SMB_FID_QLOCK_PID, ReleaseFileCB->Identifier);
2858
2859     LOffset.HighPart = SMB_FID_QLOCK_HIGH;
2860     LOffset.LowPart = SMB_FID_QLOCK_LOW;
2861     LLength.HighPart = 0;
2862     LLength.LowPart = SMB_FID_QLOCK_LENGTH;
2863
2864     lock_ObtainWrite(&scp->rw);
2865
2866     code = cm_SyncOp(scp, NULL, userp, &req, 0, CM_SCACHESYNC_LOCK);
2867     if (code == 0)
2868     {
2869         code = cm_Unlock(scp, sLockType, LOffset, LLength, key, 0, userp, &req);
2870
2871         cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_LOCK);
2872
2873         if (code == CM_ERROR_RANGE_NOT_LOCKED)
2874         {
2875             osi_Log3(afsd_logp, "RDR_ReleaseFileAccess Range Not Locked -- FileAccess 0x%x ProcessId 0x%x HandleId 0x%x",
2876                      ReleaseFileCB->FileAccess, ReleaseFileCB->ProcessId, ReleaseFileCB->Identifier);
2877         }
2878     }
2879
2880     lock_ReleaseWrite(&scp->rw);
2881
2882     osi_Log0(afsd_logp, "RDR_ReleaseFileAccessEntry SUCCESS");
2883 }
2884
2885 static const char *
2886 HexCheckSum(unsigned char * buf, int buflen, unsigned char * md5cksum)
2887 {
2888     int i, k;
2889     static char tr[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
2890
2891     if (buflen < 33)
2892         return "buffer length too small to HexCheckSum";
2893
2894     for (i=0;i<16;i++) {
2895         k = md5cksum[i];
2896
2897         buf[i*2] = tr[k / 16];
2898         buf[i*2+1] = tr[k % 16];
2899     }
2900     buf[32] = '\0';
2901
2902     return buf;
2903 }
2904
2905 /*
2906  * Extent requests from the file system are triggered when a file
2907  * page is not resident in the Windows cache.  The file system is
2908  * responsible for loading the page but cannot block the request
2909  * while doing so.  The AFS Redirector forwards the requests to
2910  * the AFS cache manager while indicating to Windows that the page
2911  * is not yet available.  A polling operation will then ensue with
2912  * the AFS Redirector issuing a RDR_RequestFileExtentsXXX call for
2913  * each poll attempt.  As each request is received and processed
2914  * by a separate worker thread in the service, this can lead to
2915  * contention by multiple threads attempting to claim the same
2916  * cm_buf_t objects.  Therefore, it is important that
2917  *
2918  *  (a) the service avoid processing more than one overlapping
2919  *      extent request at a time
2920  *  (b) background daemon processing be used to avoid blocking
2921  *      of ioctl threads
2922  *
2923  * Beginning with the 20091122 build of the redirector, the redirector
2924  * will not issue an additional RDR_RequestFileExtentsXXX call for
2925  * each poll request.  Instead, afsd_service is required to track
2926  * the requests and return them to the redirector or fail the
2927  * portions of the request that cannot be satisfied.
2928  *
2929  * The request processing returns any extents that can be returned
2930  * immediately to the redirector.  The rest of the requested range(s)
2931  * are queued as background operations using RDR_BkgFetch().
2932  */
2933
2934 /* do the background fetch. */
2935 afs_int32
2936 RDR_BkgFetch(cm_scache_t *scp, afs_uint32 p1, afs_uint32 p2, afs_uint32 p3, afs_uint32 p4,
2937              cm_user_t *userp, cm_req_t *reqp)
2938 {
2939     osi_hyper_t length;
2940     osi_hyper_t base;
2941     osi_hyper_t offset;
2942     osi_hyper_t end;
2943     osi_hyper_t fetched;
2944     osi_hyper_t tblocksize;
2945     afs_int32 code;
2946     int rwheld = 0;
2947     cm_buf_t *bufp = NULL;
2948     DWORD dwResultBufferLength;
2949     AFSSetFileExtentsCB *pResultCB;
2950     DWORD status;
2951     afs_uint32 count=0;
2952     AFSFileID FileId;
2953     int reportErrorToRedir = 0;
2954     int force_retry = 0;
2955
2956     FileId.Cell = scp->fid.cell;
2957     FileId.Volume = scp->fid.volume;
2958     FileId.Vnode = scp->fid.vnode;
2959     FileId.Unique = scp->fid.unique;
2960     FileId.Hash = scp->fid.hash;
2961
2962     fetched.LowPart = 0;
2963     fetched.HighPart = 0;
2964     tblocksize = ConvertLongToLargeInteger(cm_data.buf_blockSize);
2965     base.LowPart = p1;
2966     base.HighPart = p2;
2967     length.LowPart = p3;
2968     length.HighPart = p4;
2969
2970     end = LargeIntegerAdd(base, length);
2971
2972     osi_Log5(afsd_logp, "Starting BKG Fetch scp 0x%p offset 0x%x:%x length 0x%x:%x",
2973              scp, p2, p1, p4, p3);
2974
2975     /*
2976      * Make sure we have a callback.
2977      * This is necessary so that we can return access denied
2978      * if a callback cannot be granted.
2979      */
2980     lock_ObtainWrite(&scp->rw);
2981     code = cm_SyncOp(scp, NULL, userp, reqp, PRSFS_READ,
2982                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
2983     if (code) {
2984         lock_ReleaseWrite(&scp->rw);
2985         osi_Log2(afsd_logp, "RDR_BkgFetch cm_SyncOp failure scp=0x%p code=0x%x",
2986                  scp, code);
2987         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
2988         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
2989         return code;
2990     }
2991     lock_ReleaseWrite(&scp->rw);
2992
2993     dwResultBufferLength = (DWORD)(sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (length.QuadPart / cm_data.blockSize + 1));
2994     pResultCB = (AFSSetFileExtentsCB *)malloc( dwResultBufferLength );
2995     if (!pResultCB)
2996         return CM_ERROR_RETRY;
2997
2998     memset( pResultCB, '\0', dwResultBufferLength );
2999     pResultCB->FileId = FileId;
3000
3001     for ( code = 0, offset = base;
3002           code == 0 && LargeIntegerLessThan(offset, end);
3003           offset = LargeIntegerAdd(offset, tblocksize) )
3004     {
3005         int bBufRelease = TRUE;
3006
3007         if (rwheld) {
3008             lock_ReleaseWrite(&scp->rw);
3009             rwheld = 0;
3010         }
3011
3012         code = buf_Get(scp, &offset, reqp, &bufp);
3013         if (code) {
3014             /*
3015              * any error from buf_Get() is non-fatal.
3016              * we need to re-queue this extent fetch.
3017              */
3018             force_retry = 1;
3019             break;
3020         }
3021
3022         if (!rwheld) {
3023             lock_ObtainWrite(&scp->rw);
3024             rwheld = 1;
3025         }
3026
3027         code = cm_GetBuffer(scp, bufp, NULL, userp, reqp);
3028         if (code == 0) {
3029             if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3030 #ifdef VALIDATE_CHECK_SUM
3031 #ifdef ODS_DEBUG
3032                 char md5dbg[33];
3033                 char dbgstr[1024];
3034 #endif
3035 #endif
3036                 if (bufp->flags & CM_BUF_DIRTY)
3037                     cm_BufWrite(scp, &bufp->offset, cm_data.buf_blockSize, CM_BUF_WRITE_SCP_LOCKED, userp, reqp);
3038
3039                 lock_ObtainWrite(&buf_globalLock);
3040                 if (!(bufp->flags & CM_BUF_DIRTY) &&
3041                     bufp->cmFlags == 0 &&
3042                     !(bufp->qFlags & CM_BUF_QREDIR)) {
3043                     buf_InsertToRedirQueue(scp, bufp);
3044                     lock_ReleaseWrite(&buf_globalLock);
3045
3046 #ifdef VALIDATE_CHECK_SUM
3047                     buf_ComputeCheckSum(bufp);
3048 #endif
3049                     pResultCB->FileExtents[count].Flags = 0;
3050                     pResultCB->FileExtents[count].FileOffset.QuadPart = bufp->offset.QuadPart;
3051                     pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3052                     pResultCB->FileExtents[count].Length = cm_data.blockSize;
3053                     count++;
3054                     fetched = LargeIntegerAdd(fetched, tblocksize);
3055                     bBufRelease = FALSE;
3056
3057 #ifdef VALIDATE_CHECK_SUM
3058 #ifdef ODS_DEBUG
3059                     HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3060                     snprintf( dbgstr, 1024,
3061                               "RDR_BkgFetch md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3062                               md5dbg,
3063                               scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3064                               pResultCB->FileExtents[count].FileOffset.HighPart,
3065                               pResultCB->FileExtents[count].FileOffset.LowPart,
3066                               pResultCB->FileExtents[count].CacheOffset.HighPart,
3067                               pResultCB->FileExtents[count].CacheOffset.LowPart);
3068                     OutputDebugStringA( dbgstr);
3069 #endif
3070 #endif
3071                     osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3072                               bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3073                 } else {
3074                     lock_ReleaseWrite(&buf_globalLock);
3075                     if ((bufp->cmFlags != 0) || (bufp->flags & CM_BUF_DIRTY)) {
3076                         /* An I/O operation is already in progress */
3077                         force_retry = 1;
3078                         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",
3079                                   bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3080                     } else {
3081                         osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3082                                   bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3083                     }
3084                 }
3085             } else {
3086                 osi_Log4(afsd_logp, "RDR_BkgFetch Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3087                           bufp, bufp->offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3088             }
3089         } else {
3090             /*
3091              * depending on what the error from cm_GetBuffer is
3092              * it may or may not be fatal.  Only return fatal errors.
3093              * Re-queue a request for others.
3094              */
3095             osi_Log5(afsd_logp, "RDR_BkgFetch Extent2FS FAILURE bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x code 0x%x",
3096                       bufp, offset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize, code);
3097             switch (code) {
3098             case CM_ERROR_NOACCESS:
3099             case CM_ERROR_NOSUCHFILE:
3100             case CM_ERROR_NOSUCHPATH:
3101             case CM_ERROR_NOSUCHVOLUME:
3102             case CM_ERROR_NOSUCHCELL:
3103             case CM_ERROR_INVAL:
3104             case CM_ERROR_BADFD:
3105             case CM_ERROR_CLOCKSKEW:
3106             case RXKADNOAUTH:
3107             case CM_ERROR_QUOTA:
3108             case CM_ERROR_LOCK_CONFLICT:
3109             case EIO:
3110                 /*
3111                  * these are fatal errors.  deliver what we can
3112                  * and halt.
3113                  */
3114                 reportErrorToRedir = 1;
3115                 break;
3116             default:
3117                 /*
3118                  * non-fatal errors.  re-queue the exent
3119                  */
3120                 code = CM_ERROR_RETRY;
3121                 force_retry = 1;
3122             }
3123         }
3124
3125         if (bBufRelease)
3126             buf_Release(bufp);
3127     }
3128
3129     if (!rwheld) {
3130         lock_ObtainWrite(&scp->rw);
3131         rwheld = 1;
3132     }
3133
3134     /* wakeup anyone who is waiting */
3135     if (scp->flags & CM_SCACHEFLAG_WAITING) {
3136         osi_Log1(afsd_logp, "RDR Bkg Fetch Waking scp 0x%p", scp);
3137         osi_Wakeup((LONG_PTR) &scp->flags);
3138     }
3139     lock_ReleaseWrite(&scp->rw);
3140
3141     if (count > 0) {
3142         pResultCB->ExtentCount = count;
3143         RDR_SetFileExtents( pResultCB, dwResultBufferLength);
3144     }
3145     free(pResultCB);
3146
3147     if (reportErrorToRedir) {
3148         smb_MapNTError(cm_MapRPCError(code, reqp), &status, TRUE);
3149         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3150     }
3151
3152     osi_Log4(afsd_logp, "Ending BKG Fetch scp 0x%p code 0x%x fetched 0x%x:%x",
3153              scp, code, fetched.HighPart, fetched.LowPart);
3154
3155     return force_retry ? CM_ERROR_RETRY : code;
3156 }
3157
3158
3159 BOOL
3160 RDR_RequestFileExtentsAsync( IN cm_user_t *userp,
3161                              IN AFSFileID FileId,
3162                              IN AFSRequestExtentsCB *RequestExtentsCB,
3163                              IN BOOL bWow64,
3164                              IN OUT DWORD * ResultBufferLength,
3165                              IN OUT AFSSetFileExtentsCB **ResultCB)
3166 {
3167     AFSSetFileExtentsCB *pResultCB = NULL;
3168     DWORD Length;
3169     DWORD count;
3170     DWORD status;
3171     cm_scache_t *scp = NULL;
3172     cm_fid_t    Fid;
3173     cm_buf_t    *bufp;
3174     afs_uint32  code = 0;
3175     osi_hyper_t thyper;
3176     LARGE_INTEGER ByteOffset, BeginOffset, EndOffset, QueueOffset;
3177     afs_uint32  QueueLength;
3178     cm_req_t    req;
3179     BOOLEAN     bBufRelease = TRUE;
3180
3181     RDR_InitReq(&req, bWow64);
3182     req.flags |= CM_REQ_NORETRY;
3183
3184     osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3185               FileId.Cell, FileId.Volume,
3186               FileId.Vnode, FileId.Unique);
3187     osi_Log4(afsd_logp, "... Flags 0x%x ByteOffset 0x%x:%x Length 0x%x",
3188              RequestExtentsCB->Flags,
3189              RequestExtentsCB->ByteOffset.HighPart, RequestExtentsCB->ByteOffset.LowPart,
3190              RequestExtentsCB->Length);
3191     Length = sizeof( AFSSetFileExtentsCB) + sizeof( AFSFileExtentCB) * (RequestExtentsCB->Length / cm_data.blockSize + 1);
3192
3193     pResultCB = *ResultCB = (AFSSetFileExtentsCB *)malloc( Length );
3194     if (*ResultCB == NULL) {
3195         *ResultBufferLength = 0;
3196         return FALSE;
3197     }
3198     *ResultBufferLength = Length;
3199
3200     memset( pResultCB, '\0', Length );
3201     pResultCB->FileId = FileId;
3202
3203     Fid.cell = FileId.Cell;
3204     Fid.volume = FileId.Volume;
3205     Fid.vnode = FileId.Vnode;
3206     Fid.unique = FileId.Unique;
3207     Fid.hash = FileId.Hash;
3208
3209     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3210     if (code) {
3211         osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync cm_GetSCache FID failure code=0x%x",
3212                   code);
3213         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3214         return FALSE;
3215     }
3216
3217     /*
3218      * Make sure we have a callback.
3219      * This is necessary so that we can return access denied
3220      * if a callback cannot be granted.
3221      */
3222     lock_ObtainWrite(&scp->rw);
3223     code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
3224                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3225     lock_ReleaseWrite(&scp->rw);
3226     if (code) {
3227         cm_ReleaseSCache(scp);
3228         osi_Log2(afsd_logp, "RDR_RequestFileExtentsAsync cm_SyncOp failure scp=0x%p code=0x%x",
3229                  scp, code);
3230         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3231         RDR_SetFileStatus( &scp->fid, &userp->authgroup, status);
3232         return FALSE;
3233     }
3234
3235     /* Allocate the extents from the buffer package */
3236     for ( count = 0,
3237           ByteOffset = BeginOffset = RequestExtentsCB->ByteOffset,
3238           EndOffset.QuadPart = ByteOffset.QuadPart + RequestExtentsCB->Length;
3239           code == 0 && ByteOffset.QuadPart < EndOffset.QuadPart;
3240           ByteOffset.QuadPart += cm_data.blockSize)
3241     {
3242         BOOL bHaveBuffer = FALSE;
3243
3244         QueueLength = 0;
3245         thyper.QuadPart = ByteOffset.QuadPart;
3246
3247         code = buf_Get(scp, &thyper, &req, &bufp);
3248         if (code == 0) {
3249             lock_ObtainMutex(&bufp->mx);
3250             bBufRelease = TRUE;
3251
3252             if (bufp->qFlags & CM_BUF_QREDIR) {
3253                 bHaveBuffer = TRUE;
3254             } else if (bufp->flags & CM_BUF_DIRTY) {
3255                 bHaveBuffer = FALSE;
3256 #if 0
3257                 code = buf_CleanAsyncLocked(scp, bufp, &req, 0, NULL);
3258                 switch (code) {
3259                 case 0:
3260                     bHaveBuffer = TRUE;
3261                     break;
3262                 case CM_ERROR_RETRY:
3263                     /* Couldn't flush it, obtain it asynchronously so we don't block the thread. */
3264                     bHaveBuffer = FALSE;
3265                     code = 0;
3266                     break;
3267                 default:
3268                     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3269                     RDR_SetFileStatus(&FileId, &userp->authgroup, status);
3270                     bHaveBuffer = FALSE;
3271                     code = 0;
3272                 }
3273 #endif
3274             } else {
3275                 osi_hyper_t minLength;  /* effective end of file */
3276
3277                 lock_ObtainRead(&scp->rw);
3278                 bHaveBuffer = cm_HaveBuffer(scp, bufp, TRUE);
3279
3280                 if (LargeIntegerGreaterThan(scp->length, scp->serverLength))
3281                     minLength = scp->serverLength;
3282                 else
3283                     minLength = scp->length;
3284
3285                 if (LargeIntegerGreaterThanOrEqualTo(bufp->offset, minLength)) {
3286                     if (!bHaveBuffer) {
3287                         memset(bufp->datap, 0, cm_data.buf_blockSize);
3288                         bufp->dataVersion = scp->dataVersion;
3289                         bHaveBuffer = TRUE;
3290                     }
3291                     else if (bufp->dataVersion == CM_BUF_VERSION_BAD) {
3292                         bufp->dataVersion = scp->dataVersion;
3293                     }
3294                 }
3295                 else if ((RequestExtentsCB->Flags & AFS_EXTENT_FLAG_CLEAN) &&
3296                          ByteOffset.QuadPart <= bufp->offset.QuadPart &&
3297                          EndOffset.QuadPart >= bufp->offset.QuadPart + cm_data.blockSize)
3298                 {
3299                     memset(bufp->datap, 0, cm_data.blockSize);
3300                     bufp->dataVersion = scp->dataVersion;
3301                     buf_SetDirty(bufp, &req, 0, cm_data.blockSize, userp);
3302                     bHaveBuffer = TRUE;
3303                 }
3304                 lock_ReleaseRead(&scp->rw);
3305             }
3306
3307             /*
3308              * if this buffer is already up to date, skip it.
3309              */
3310             if (bHaveBuffer) {
3311                 if (ByteOffset.QuadPart == BeginOffset.QuadPart) {
3312                     BeginOffset.QuadPart += cm_data.blockSize;
3313                 } else {
3314                     QueueLength = (afs_uint32)(ByteOffset.QuadPart - BeginOffset.QuadPart);
3315                     QueueOffset = BeginOffset;
3316                     BeginOffset = ByteOffset;
3317                 }
3318
3319                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3320 #ifdef VALIDATE_CHECK_SUM
3321 #ifdef ODS_DEBUG
3322                     char md5dbg[33];
3323                     char dbgstr[1024];
3324 #endif
3325 #endif
3326                     lock_ObtainWrite(&buf_globalLock);
3327                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3328                         buf_InsertToRedirQueue(scp, bufp);
3329                         lock_ReleaseWrite(&buf_globalLock);
3330
3331 #ifdef VALIDATE_CHECK_SUM
3332                         buf_ComputeCheckSum(bufp);
3333 #endif
3334                         /* we already have the buffer, return it now */
3335                         pResultCB->FileExtents[count].Flags = 0;
3336                         pResultCB->FileExtents[count].FileOffset = ByteOffset;
3337                         pResultCB->FileExtents[count].CacheOffset.QuadPart = bufp->datap - RDR_extentBaseAddress;
3338                         pResultCB->FileExtents[count].Length = cm_data.blockSize;
3339                         count++;
3340
3341                         bBufRelease = FALSE;
3342
3343 #ifdef VALIDATE_CHECK_SUM
3344 #ifdef ODS_DEBUG
3345                         HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3346                         snprintf( dbgstr, 1024,
3347                                   "RDR_RequestFileExtentsAsync md5 %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3348                                   md5dbg,
3349                                   scp->fid.volume, scp->fid.vnode, scp->fid.unique,
3350                                   pResultCB->FileExtents[count].FileOffset.HighPart,
3351                                   pResultCB->FileExtents[count].FileOffset.LowPart,
3352                                   pResultCB->FileExtents[count].CacheOffset.HighPart,
3353                                   pResultCB->FileExtents[count].CacheOffset.LowPart);
3354                         OutputDebugStringA( dbgstr);
3355 #endif
3356 #endif
3357                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3358                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3359                     } else {
3360                         lock_ReleaseWrite(&buf_globalLock);
3361                     }
3362                 } else {
3363                     if (bBufRelease) {
3364                         /*
3365                          * The service is not handing off the extent to the redirector in this pass.
3366                          * However, we know the buffer is in recent use so move the buffer to the
3367                          * front of the queue
3368                          */
3369                         lock_ObtainWrite(&buf_globalLock);
3370                         buf_MoveToHeadOfRedirQueue(scp, bufp);
3371                         lock_ReleaseWrite(&buf_globalLock);
3372
3373                         osi_Log4(afsd_logp, "RDR_RequestFileExtentsAsync Extent2FS Already held by Redirector bufp 0x%p foffset 0x%p coffset 0x%p len 0x%x",
3374                                  bufp, ByteOffset.QuadPart, bufp->datap - RDR_extentBaseAddress, cm_data.blockSize);
3375                     }
3376                 }
3377             }
3378             lock_ReleaseMutex(&bufp->mx);
3379             if (bBufRelease)
3380                 buf_Release(bufp);
3381
3382             if (QueueLength) {
3383                 cm_QueueBKGRequest(scp, RDR_BkgFetch, QueueOffset.LowPart, QueueOffset.HighPart,
3384                                    QueueLength, 0, userp, &req);
3385                 osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync Queued a Background Fetch offset 0x%x:%x length 0x%x",
3386                          QueueOffset.HighPart, QueueOffset.LowPart, QueueLength);
3387             }
3388         } else {
3389             /* No error from buf_Get() can be fatal */
3390             osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync buf_Get FAILURE offset 0x%x:%x code 0x%x",
3391                      BeginOffset.HighPart, BeginOffset.LowPart, code);
3392         }
3393     }
3394
3395     if (BeginOffset.QuadPart != EndOffset.QuadPart) {
3396         afs_uint32 length = (afs_uint32)(EndOffset.QuadPart - BeginOffset.QuadPart);
3397
3398         cm_QueueBKGRequest(scp, RDR_BkgFetch, BeginOffset.LowPart, BeginOffset.HighPart,
3399                            length, 0, userp, &req);
3400         osi_Log3(afsd_logp, "RDR_RequestFileExtentsAsync Queued a Background Fetch offset 0x%x:%x length 0x%x",
3401                   BeginOffset.HighPart, BeginOffset.LowPart, length);
3402     }
3403     cm_ReleaseSCache(scp);
3404
3405     (*ResultCB)->ExtentCount = count;
3406     osi_Log1(afsd_logp, "RDR_RequestFileExtentsAsync replying with 0x%x extent records", count);
3407     return FALSE;
3408 }
3409
3410 /*
3411  * When processing an extent release the extents must be accepted back by
3412  * the service even if there is an error condition returned to the redirector.
3413  * For example, there may no longer be a callback present or the file may
3414  * have been deleted on the file server.  Regardless, the extents must be
3415  * put back into the pool.
3416  */
3417 void
3418 RDR_ReleaseFileExtents( IN cm_user_t *userp,
3419                         IN AFSFileID FileId,
3420                         IN AFSReleaseExtentsCB *ReleaseExtentsCB,
3421                         IN BOOL bWow64,
3422                         IN DWORD ResultBufferLength,
3423                         IN OUT AFSCommResult **ResultCB)
3424 {
3425     DWORD count;
3426     cm_scache_t *scp = NULL;
3427     cm_fid_t    Fid;
3428     cm_buf_t    *bufp;
3429     afs_uint32  code;
3430     osi_hyper_t thyper;
3431     cm_req_t    req;
3432     int         dirty = 0;
3433     int         released = 0;
3434     int         deleted = 0;
3435     DWORD       status;
3436 #ifdef ODS_DEBUG
3437 #ifdef VALIDATE_CHECK_SUM
3438     char md5dbg[33], md5dbg2[33], md5dbg3[33];
3439 #endif
3440     char dbgstr[1024];
3441 #endif
3442
3443     RDR_InitReq(&req, bWow64);
3444
3445     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
3446               FileId.Cell, FileId.Volume,
3447               FileId.Vnode, FileId.Unique);
3448
3449     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
3450     if (!(*ResultCB))
3451         return;
3452
3453     memset( *ResultCB,
3454             '\0',
3455             sizeof( AFSCommResult));
3456
3457     /* Process the release */
3458     Fid.cell = FileId.Cell;
3459     Fid.volume = FileId.Volume;
3460     Fid.vnode = FileId.Vnode;
3461     Fid.unique = FileId.Unique;
3462     Fid.hash = FileId.Hash;
3463
3464     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3465     if (code) {
3466         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3467         (*ResultCB)->ResultStatus = status;
3468         osi_Log2(afsd_logp, "RDR_ReleaseFileExtents cm_GetSCache FID failure code=0x%x status=0x%x",
3469                   code, status);
3470     }
3471
3472     deleted = scp && (scp->flags & CM_SCACHEFLAG_DELETED);
3473
3474     /*
3475      * We do not stop processing as a result of being unable to find the cm_scache object.
3476      * If this occurs something really bad has happened since the cm_scache object must have
3477      * been recycled while extents were held by the redirector.  However, we will be resilient
3478      * and carry on without it.
3479      *
3480      * If the file is known to be deleted, there is no point attempting to ask the
3481      * file server about it or update the attributes.
3482      */
3483     if (scp && ReleaseExtentsCB->AllocationSize.QuadPart != scp->length.QuadPart &&
3484         !deleted)
3485     {
3486         cm_attr_t setAttr;
3487
3488         memset(&setAttr, 0, sizeof(cm_attr_t));
3489         lock_ObtainWrite(&scp->rw);
3490         if (ReleaseExtentsCB->AllocationSize.QuadPart != scp->length.QuadPart) {
3491
3492             osi_Log4(afsd_logp, "RDR_ReleaseFileExtents new length fid vol 0x%x vno 0x%x length 0x%x:%x",
3493                       scp->fid.volume, scp->fid.vnode,
3494                       ReleaseExtentsCB->AllocationSize.HighPart,
3495                       ReleaseExtentsCB->AllocationSize.LowPart);
3496
3497             setAttr.mask |= CM_ATTRMASK_LENGTH;
3498             setAttr.length.LowPart = ReleaseExtentsCB->AllocationSize.LowPart;
3499             setAttr.length.HighPart = ReleaseExtentsCB->AllocationSize.HighPart;
3500         }
3501         lock_ReleaseWrite(&scp->rw);
3502         if (setAttr.mask)
3503             code = cm_SetAttr(scp, &setAttr, userp, &req);
3504     }
3505
3506     for ( count = 0; count < ReleaseExtentsCB->ExtentCount; count++) {
3507         AFSFileExtentCB * pExtent = &ReleaseExtentsCB->FileExtents[count];
3508
3509         thyper.QuadPart = pExtent->FileOffset.QuadPart;
3510
3511         bufp = buf_Find(&Fid, &thyper);
3512         if (bufp) {
3513             if (pExtent->Flags & AFS_EXTENT_FLAG_UNKNOWN) {
3514                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3515                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3516                               Fid.volume, Fid.vnode,
3517                               pExtent->FileOffset.HighPart,
3518                               pExtent->FileOffset.LowPart);
3519                     osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; previously released",
3520                               pExtent->CacheOffset.HighPart,
3521                               pExtent->CacheOffset.LowPart);
3522                 } else {
3523                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3524                               Fid.volume, Fid.vnode,
3525                               pExtent->FileOffset.HighPart,
3526                               pExtent->FileOffset.LowPart);
3527                     osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; owned by redirector",
3528                               pExtent->CacheOffset.HighPart,
3529                               pExtent->CacheOffset.LowPart);
3530                 }
3531                 buf_Release(bufp);
3532                 continue;
3533             }
3534
3535             if (pExtent->Flags & AFS_EXTENT_FLAG_IN_USE) {
3536                 osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3537                           Fid.volume, Fid.vnode,
3538                           pExtent->FileOffset.HighPart,
3539                           pExtent->FileOffset.LowPart);
3540                 osi_Log2(afsd_logp, "... coffset 0x%x:%x IN_USE by file system",
3541                           pExtent->CacheOffset.HighPart,
3542                           pExtent->CacheOffset.LowPart);
3543
3544                 /* Move the buffer to the front of the queue */
3545                 lock_ObtainWrite(&buf_globalLock);
3546                 buf_MoveToHeadOfRedirQueue(scp, bufp);
3547                 lock_ReleaseWrite(&buf_globalLock);
3548                 buf_Release(bufp);
3549                 continue;
3550             }
3551
3552             if (bufp->datap - RDR_extentBaseAddress == pExtent->CacheOffset.QuadPart) {
3553                 if (!(bufp->qFlags & CM_BUF_QREDIR)) {
3554                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents extent vol 0x%x vno 0x%x foffset 0x%x:%x not held by file system",
3555                              Fid.volume, Fid.vnode, pExtent->FileOffset.HighPart,
3556                              pExtent->FileOffset.LowPart);
3557                     osi_Log2(afsd_logp, "... coffset 0x%x:%x",
3558                              pExtent->CacheOffset.HighPart,
3559                              pExtent->CacheOffset.LowPart);
3560                 } else {
3561                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtents bufp 0x%p vno 0x%x foffset 0x%x:%x",
3562                               bufp, bufp->fid.vnode, pExtent->FileOffset.HighPart,
3563                               pExtent->FileOffset.LowPart);
3564                     osi_Log2(afsd_logp, "... coffset 0x%x:%x",
3565                              pExtent->CacheOffset.HighPart,
3566                              pExtent->CacheOffset.LowPart);
3567
3568                     if (pExtent->Flags || ReleaseExtentsCB->Flags) {
3569                         lock_ObtainMutex(&bufp->mx);
3570                         if ( (ReleaseExtentsCB->Flags & AFS_EXTENT_FLAG_RELEASE) ||
3571                              (pExtent->Flags & AFS_EXTENT_FLAG_RELEASE) )
3572                         {
3573                             if (bufp->qFlags & CM_BUF_QREDIR) {
3574                                 lock_ObtainWrite(&buf_globalLock);
3575                                 if (bufp->qFlags & CM_BUF_QREDIR) {
3576                                     buf_RemoveFromRedirQueue(scp, bufp);
3577                                     buf_ReleaseLocked(bufp, TRUE);
3578                                 }
3579                                 lock_ReleaseWrite(&buf_globalLock);
3580                             }
3581 #ifdef ODS_DEBUG
3582                             snprintf( dbgstr, 1024,
3583                                       "RDR_ReleaseFileExtents releasing: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3584                                       Fid.volume, Fid.vnode, Fid.unique,
3585                                       pExtent->FileOffset.HighPart,
3586                                       pExtent->FileOffset.LowPart,
3587                                       pExtent->CacheOffset.HighPart,
3588                                       pExtent->CacheOffset.LowPart);
3589                             OutputDebugStringA( dbgstr);
3590 #endif
3591                             released++;
3592                         } else {
3593 #ifdef ODS_DEBUG
3594                             snprintf( dbgstr, 1024,
3595                                       "RDR_ReleaseFileExtents not releasing: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3596                                       Fid.volume, Fid.vnode, Fid.unique,
3597                                       pExtent->FileOffset.HighPart,
3598                                       pExtent->FileOffset.LowPart,
3599                                       pExtent->CacheOffset.HighPart,
3600                                       pExtent->CacheOffset.LowPart);
3601                             OutputDebugStringA( dbgstr);
3602 #endif
3603                             osi_Log4( afsd_logp, "RDR_ReleaseFileExtents not releasing vol 0x%x vno 0x%x foffset 0x%x:%x",
3604                                       Fid.volume, Fid.vnode,
3605                                       pExtent->FileOffset.HighPart,
3606                                       pExtent->FileOffset.LowPart);
3607                             osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3608                                       pExtent->CacheOffset.HighPart,
3609                                       pExtent->CacheOffset.LowPart);
3610                         }
3611
3612                         if ( (ReleaseExtentsCB->Flags & AFS_EXTENT_FLAG_DIRTY) ||
3613                              (pExtent->Flags & AFS_EXTENT_FLAG_DIRTY) )
3614                         {
3615 #ifdef VALIDATE_CHECK_SUM
3616 #ifdef ODS_DEBUG
3617                             HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3618 #endif
3619
3620                             /*
3621                              * if the saved checksum matches the checksum of the current state of the buffer
3622                              * then the buffer is the same as what was given to the kernel.
3623                              */
3624                             if ( buf_ValidateCheckSum(bufp) ) {
3625                                 buf_ComputeCheckSum(bufp);
3626
3627                                 if (pExtent->Flags & AFS_EXTENT_FLAG_MD5_SET)
3628                                 {
3629 #ifdef ODS_DEBUG
3630                                     HexCheckSum(md5dbg2, sizeof(md5dbg2), pExtent->MD5);
3631                                     HexCheckSum(md5dbg3, sizeof(md5dbg3), bufp->md5cksum);
3632 #endif
3633                                     if (memcmp(bufp->md5cksum, pExtent->MD5, 16))
3634                                     {
3635 #ifdef ODS_DEBUG
3636                                         snprintf( dbgstr, 1024,
3637                                                   "RDR_ReleaseFileExtents dirty flag set but not dirty and user != kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3638                                                   md5dbg, md5dbg2,md5dbg3,
3639                                                   Fid.volume, Fid.vnode, Fid.unique,
3640                                                   pExtent->FileOffset.HighPart,
3641                                                   pExtent->FileOffset.LowPart,
3642                                                   pExtent->CacheOffset.HighPart,
3643                                                   pExtent->CacheOffset.LowPart);
3644                                         OutputDebugStringA( dbgstr);
3645 #endif
3646                                         osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag set and checksums do not match! vol 0x%x vno 0x%x foffset 0x%x:%x",
3647                                                   Fid.volume, Fid.vnode,
3648                                                   pExtent->FileOffset.HighPart,
3649                                                   pExtent->FileOffset.LowPart);
3650                                         osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3651                                                   pExtent->CacheOffset.HighPart,
3652                                                   pExtent->CacheOffset.LowPart);
3653                                         buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3654                                         dirty++;
3655                                     } else {
3656 #ifdef ODS_DEBUG
3657                                         snprintf( dbgstr, 1024,
3658                                                   "RDR_ReleaseFileExtents dirty flag set but not dirty and user == kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3659                                                   md5dbg, md5dbg2, md5dbg3,
3660                                                   Fid.volume, Fid.vnode, Fid.unique,
3661                                                   pExtent->FileOffset.HighPart,
3662                                                   pExtent->FileOffset.LowPart,
3663                                                   pExtent->CacheOffset.HighPart,
3664                                                   pExtent->CacheOffset.LowPart);
3665                                         OutputDebugStringA( dbgstr);
3666 #endif
3667                                         osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag set but extent has not changed vol 0x%x vno 0x%x foffset 0x%x:%x",
3668                                                   Fid.volume, Fid.vnode,
3669                                                   pExtent->FileOffset.HighPart,
3670                                                   pExtent->FileOffset.LowPart);
3671                                         osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3672                                                   pExtent->CacheOffset.HighPart,
3673                                                   pExtent->CacheOffset.LowPart);
3674                                     }
3675                                 } else {
3676 #ifdef ODS_DEBUG
3677                                         snprintf( dbgstr, 1024,
3678                                                   "RDR_ReleaseFileExtents dirty flag set but not dirty: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3679                                                   Fid.volume, Fid.vnode, Fid.unique,
3680                                                   pExtent->FileOffset.HighPart,
3681                                                   pExtent->FileOffset.LowPart,
3682                                                   pExtent->CacheOffset.HighPart,
3683                                                   pExtent->CacheOffset.LowPart);
3684                                         OutputDebugStringA( dbgstr);
3685 #endif
3686                                         osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag set but extent has not changed vol 0x%x vno 0x%x foffset 0x%x:%x",
3687                                                   Fid.volume, Fid.vnode,
3688                                                   pExtent->FileOffset.HighPart,
3689                                                   pExtent->FileOffset.LowPart);
3690                                         osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3691                                                   pExtent->CacheOffset.HighPart,
3692                                                   pExtent->CacheOffset.LowPart);
3693                                 }
3694                             } else {
3695                                 buf_ComputeCheckSum(bufp);
3696 #ifdef ODS_DEBUG
3697                                 if (pExtent->Flags & AFS_EXTENT_FLAG_MD5_SET)
3698                                 {
3699                                     HexCheckSum(md5dbg3, sizeof(md5dbg3), bufp->md5cksum);
3700                                     if (memcmp(bufp->md5cksum, pExtent->MD5, 16))
3701                                     {
3702                                         snprintf( dbgstr, 1024,
3703                                                   "RDR_ReleaseFileExtents dirty flag set and dirty and user != kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3704                                                   md5dbg, md5dbg2,md5dbg3,
3705                                                   Fid.volume, Fid.vnode, Fid.unique,
3706                                                   pExtent->FileOffset.HighPart,
3707                                                   pExtent->FileOffset.LowPart,
3708                                                   pExtent->CacheOffset.HighPart,
3709                                                   pExtent->CacheOffset.LowPart);
3710                                         OutputDebugStringA( dbgstr);
3711                                     } else {
3712                                         snprintf( dbgstr, 1024,
3713                                                   "RDR_ReleaseFileExtents dirty flag set and dirty and user == kernel: old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3714                                                   md5dbg, md5dbg2,md5dbg3,
3715                                                   Fid.volume, Fid.vnode, Fid.unique,
3716                                                   pExtent->FileOffset.HighPart,
3717                                                   pExtent->FileOffset.LowPart,
3718                                                   pExtent->CacheOffset.HighPart,
3719                                                   pExtent->CacheOffset.LowPart);
3720                                         OutputDebugStringA( dbgstr);
3721                                     }
3722                                 } else {
3723                                     snprintf( dbgstr, 1024,
3724                                               "RDR_ReleaseFileExtents dirty flag set: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3725                                               Fid.volume, Fid.vnode, Fid.unique,
3726                                               pExtent->FileOffset.HighPart,
3727                                               pExtent->FileOffset.LowPart,
3728                                               pExtent->CacheOffset.HighPart,
3729                                               pExtent->CacheOffset.LowPart);
3730                                     OutputDebugStringA( dbgstr);
3731                                 }
3732 #endif
3733                                 buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3734                                 dirty++;
3735                             }
3736 #else /* !VALIDATE_CHECK_SUM */
3737                             buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3738                             dirty++;
3739 #endif /* VALIDATE_CHECK_SUM */
3740                         }
3741 #ifdef VALIDATE_CHECK_SUM
3742                         else {
3743 #ifdef ODS_DEBUG
3744                             HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
3745 #endif
3746                             if ( !buf_ValidateCheckSum(bufp) ) {
3747                                 buf_ComputeCheckSum(bufp);
3748 #ifdef ODS_DEBUG
3749                                 HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
3750                                 snprintf( dbgstr, 1024,
3751                                           "RDR_ReleaseFileExtents dirty flag not set but dirty! old %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3752                                           md5dbg, md5dbg3,
3753                                           Fid.volume, Fid.vnode, Fid.unique,
3754                                           pExtent->FileOffset.HighPart,
3755                                           pExtent->FileOffset.LowPart,
3756                                           pExtent->CacheOffset.HighPart,
3757                                           pExtent->CacheOffset.LowPart);
3758                                 OutputDebugStringA( dbgstr);
3759 #endif
3760                                 osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag not set but extent has changed vol 0x%x vno 0x%x foffset 0x%x:%x",
3761                                           Fid.volume, Fid.vnode,
3762                                           pExtent->FileOffset.HighPart,
3763                                           pExtent->FileOffset.LowPart);
3764                                 osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3765                                           pExtent->CacheOffset.HighPart,
3766                                           pExtent->CacheOffset.LowPart);
3767                                 buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
3768                                 dirty++;
3769                             } else {
3770                                 buf_ComputeCheckSum(bufp);
3771 #ifdef ODS_DEBUG
3772                                 HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
3773                                 snprintf( dbgstr, 1024,
3774                                           "RDR_ReleaseFileExtents dirty flag not set: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3775                                           Fid.volume, Fid.vnode, Fid.unique,
3776                                           pExtent->FileOffset.HighPart,
3777                                           pExtent->FileOffset.LowPart,
3778                                           pExtent->CacheOffset.HighPart,
3779                                           pExtent->CacheOffset.LowPart);
3780                                 OutputDebugStringA( dbgstr);
3781 #endif
3782                                 osi_Log4( afsd_logp, "RDR_ReleaseFileExtents dirty flag not set: vol 0x%x vno 0x%x foffset 0x%x:%x",
3783                                           Fid.volume, Fid.vnode,
3784                                           pExtent->FileOffset.HighPart,
3785                                           pExtent->FileOffset.LowPart);
3786                                 osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3787                                           pExtent->CacheOffset.HighPart,
3788                                           pExtent->CacheOffset.LowPart);
3789                             }
3790                         }
3791 #endif /* VALIDATE_CHECK_SUM */
3792                         lock_ReleaseMutex(&bufp->mx);
3793                     }
3794                 }
3795             }
3796             else {
3797                 char * datap = RDR_extentBaseAddress + pExtent->CacheOffset.QuadPart;
3798                 cm_buf_t *wbp;
3799
3800                 for (wbp = cm_data.buf_allp; wbp; wbp = wbp->allp) {
3801                     if (wbp->datap == datap)
3802                         break;
3803                 }
3804
3805 #ifdef ODS_DEBUG
3806                 snprintf( dbgstr, 1024,
3807                           "RDR_ReleaseFileExtents non-matching extent vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3808                           Fid.volume, Fid.vnode, Fid.unique,
3809                           pExtent->FileOffset.HighPart,
3810                           pExtent->FileOffset.LowPart,
3811                           pExtent->CacheOffset.HighPart,
3812                           pExtent->CacheOffset.LowPart);
3813                 OutputDebugStringA( dbgstr);
3814 #endif
3815                 osi_Log4( afsd_logp, "RDR_ReleaseFileExtents non-matching extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3816                           Fid.volume, Fid.vnode,
3817                           pExtent->FileOffset.HighPart,
3818                           pExtent->FileOffset.LowPart);
3819                 osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3820                           pExtent->CacheOffset.HighPart,
3821                           pExtent->CacheOffset.LowPart);
3822                 osi_Log5( afsd_logp, "... belongs to bp 0x%p vol 0x%x vno 0x%x foffset 0x%x:%x",
3823                           wbp, wbp->fid.volume, wbp->fid.vnode, wbp->offset.HighPart, wbp->offset.LowPart);
3824             }
3825             buf_Release(bufp);
3826         }
3827         else {
3828             char * datap = RDR_extentBaseAddress + pExtent->CacheOffset.QuadPart;
3829             cm_buf_t *wbp;
3830
3831             for (wbp = cm_data.buf_allp; wbp; wbp = wbp->allp) {
3832                 if (wbp->datap == datap)
3833                     break;
3834             }
3835
3836 #ifdef ODS_DEBUG
3837             snprintf( dbgstr, 1024,
3838                       "RDR_ReleaseFileExtents unknown extent vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
3839                       Fid.volume, Fid.vnode, Fid.unique,
3840                       pExtent->FileOffset.HighPart,
3841                       pExtent->FileOffset.LowPart,
3842                       pExtent->CacheOffset.HighPart,
3843                       pExtent->CacheOffset.LowPart);
3844             OutputDebugStringA( dbgstr);
3845 #endif
3846             osi_Log4( afsd_logp, "RDR_ReleaseFileExtents unknown extent vol 0x%x vno 0x%x foffset 0x%x:%x",
3847                       Fid.volume, Fid.vnode,
3848                       pExtent->FileOffset.HighPart,
3849                       pExtent->FileOffset.LowPart);
3850             osi_Log2( afsd_logp, "... coffset 0x%x:%x",
3851                       pExtent->CacheOffset.HighPart,
3852                       pExtent->CacheOffset.LowPart);
3853             osi_Log5( afsd_logp, "... belongs to bp 0x%p vol 0x%x vno 0x%x foffset 0x%x:%x",
3854                       wbp, wbp->fid.volume, wbp->fid.vnode, wbp->offset.HighPart, wbp->offset.LowPart);
3855         }
3856     }
3857
3858     if (scp) {
3859         if (deleted) {
3860             code = 0;
3861         } else if (ReleaseExtentsCB->Flags & AFS_EXTENT_FLAG_FLUSH) {
3862             lock_ObtainWrite(&scp->rw);
3863             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
3864                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3865             lock_ReleaseWrite(&scp->rw);
3866             if (code == 0)
3867                 code = cm_FSync(scp, userp, &req, FALSE);
3868         }
3869         else if (dirty) {
3870             osi_hyper_t offset = {0,0};
3871             afs_uint32  length = 0;
3872             afs_uint32  rights = 0;
3873
3874             lock_ObtainWrite(&scp->rw);
3875             code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_WRITE,
3876                              CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
3877             lock_ReleaseWrite(&scp->rw);
3878             if (code == 0) {
3879                 /*
3880                  * there is at least one dirty extent on this file.  queue up background store
3881                  * requests for contiguous blocks
3882                  */
3883                 for ( count = 0; count < ReleaseExtentsCB->ExtentCount; count++) {
3884                     if (ReleaseExtentsCB->FileExtents[count].FileOffset.QuadPart == offset.QuadPart + length &&
3885                          length + cm_data.buf_blockSize <= cm_chunkSize)
3886                     {
3887                         length += cm_data.buf_blockSize;
3888                     } else {
3889                         if (!(offset.QuadPart == 0 && length == 0))
3890                             cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
3891                                                 length, 0, userp, &req);
3892                         offset.QuadPart = ReleaseExtentsCB->FileExtents[count].FileOffset.QuadPart;
3893                         length = cm_data.buf_blockSize;
3894                     }
3895                 }
3896                 cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
3897                                    length, 0, userp, &req);
3898             }
3899         }
3900         cm_ReleaseSCache(scp);
3901     }
3902
3903     osi_Log5(afsd_logp, "RDR_ReleaseFileExtents File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x Released %d",
3904               FileId.Cell, FileId.Volume,
3905               FileId.Vnode, FileId.Unique, released);
3906     if (code && code != CM_ERROR_WOULDBLOCK) {
3907         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
3908         (*ResultCB)->ResultStatus = status;
3909         osi_Log2(afsd_logp, "RDR_ReleaseFileExtents FAILURE code=0x%x status=0x%x",
3910                   code, status);
3911     } else {
3912         (*ResultCB)->ResultStatus = 0;
3913         osi_Log0(afsd_logp, "RDR_ReleaseFileExtents SUCCESS");
3914     }
3915     (*ResultCB)->ResultBufferLength = 0;
3916
3917     return;
3918 }
3919
3920 DWORD
3921 RDR_ProcessReleaseFileExtentsResult( IN AFSReleaseFileExtentsResultCB *ReleaseFileExtentsResultCB,
3922                                      IN DWORD ResultBufferLength)
3923 {
3924     afs_uint32  code = 0;
3925     cm_req_t    req;
3926     osi_hyper_t thyper;
3927     cm_buf_t    *bufp;
3928     unsigned int fileno, extentno, total_extents = 0;
3929     AFSReleaseFileExtentsResultFileCB *pNextFileCB;
3930 #ifdef ODS_DEBUG
3931 #ifdef VALIDATE_CHECK_SUM
3932     char md5dbg[33], md5dbg2[33], md5dbg3[33];
3933 #endif
3934     char dbgstr[1024];
3935 #endif
3936     RDR_InitReq(&req, FALSE);
3937
3938     for ( fileno = 0, pNextFileCB = &ReleaseFileExtentsResultCB->Files[0];
3939           fileno < ReleaseFileExtentsResultCB->FileCount;
3940           fileno++ ) {
3941         AFSReleaseFileExtentsResultFileCB *pFileCB = pNextFileCB;
3942         cm_user_t       *userp = NULL;
3943         cm_fid_t         Fid;
3944         cm_scache_t *    scp = NULL;
3945         int              dirty = 0;
3946         int              released = 0;
3947         int              deleted = 0;
3948         char * p;
3949
3950         userp = RDR_UserFromAuthGroup( &pFileCB->AuthGroup);
3951
3952         osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult %d.%d.%d.%d",
3953                   pFileCB->FileId.Cell, pFileCB->FileId.Volume,
3954                   pFileCB->FileId.Vnode, pFileCB->FileId.Unique);
3955
3956         /* Process the release */
3957         Fid.cell = pFileCB->FileId.Cell;
3958         Fid.volume = pFileCB->FileId.Volume;
3959         Fid.vnode = pFileCB->FileId.Vnode;
3960         Fid.unique = pFileCB->FileId.Unique;
3961         Fid.hash = pFileCB->FileId.Hash;
3962
3963         if (Fid.cell == 0) {
3964             osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult Invalid FID %d.%d.%d.%d",
3965                      Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
3966             code = CM_ERROR_INVAL;
3967             goto cleanup_file;
3968         }
3969
3970         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
3971         if (code) {
3972             osi_Log1(afsd_logp, "RDR_ProcessReleaseFileExtentsResult cm_GetSCache FID failure code=0x%x",
3973                      code);
3974             /*
3975              * A failure to find the cm_scache object cannot prevent the service
3976              * from accepting the extents back from the redirector.
3977              */
3978         }
3979
3980         deleted = scp && (scp->flags & CM_SCACHEFLAG_DELETED);
3981
3982         /* if the scp was not found, do not perform the length check */
3983         if (scp && (pFileCB->AllocationSize.QuadPart != scp->length.QuadPart)) {
3984             cm_attr_t setAttr;
3985
3986             memset(&setAttr, 0, sizeof(cm_attr_t));
3987             lock_ObtainWrite(&scp->rw);
3988             if (pFileCB->AllocationSize.QuadPart != scp->length.QuadPart) {
3989                 osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult length change vol 0x%x vno 0x%x length 0x%x:%x",
3990                           scp->fid.volume, scp->fid.vnode,
3991                           pFileCB->AllocationSize.HighPart,
3992                           pFileCB->AllocationSize.LowPart);
3993                 setAttr.mask |= CM_ATTRMASK_LENGTH;
3994                 setAttr.length.LowPart = pFileCB->AllocationSize.LowPart;
3995                 setAttr.length.HighPart = pFileCB->AllocationSize.HighPart;
3996             }
3997             lock_ReleaseWrite(&scp->rw);
3998             if (setAttr.mask)
3999                 code = cm_SetAttr(scp, &setAttr, userp, &req);
4000         }
4001
4002         for ( extentno = 0; extentno < pFileCB->ExtentCount; total_extents++, extentno++ ) {
4003             AFSFileExtentCB *pExtent = &pFileCB->FileExtents[extentno];
4004
4005             thyper.QuadPart = pExtent->FileOffset.QuadPart;
4006
4007             bufp = buf_Find(&Fid, &thyper);
4008             if (bufp) {
4009                 if (pExtent->Flags & AFS_EXTENT_FLAG_UNKNOWN) {
4010                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
4011                         osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4012                                  Fid.volume, Fid.vnode,
4013                                  pExtent->FileOffset.HighPart,
4014                                  pExtent->FileOffset.LowPart);
4015                         osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; previously released",
4016                                  pExtent->CacheOffset.HighPart,
4017                                  pExtent->CacheOffset.LowPart);
4018                     } else {
4019                         osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4020                                  Fid.volume, Fid.vnode,
4021                                  pExtent->FileOffset.HighPart,
4022                                  pExtent->FileOffset.LowPart);
4023                         osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; owned by redirector",
4024                                  pExtent->CacheOffset.HighPart,
4025                                  pExtent->CacheOffset.LowPart);
4026                     }
4027                     buf_Release(bufp);
4028                     continue;
4029                 }
4030
4031                 if (pExtent->Flags & AFS_EXTENT_FLAG_IN_USE) {
4032                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4033                               Fid.volume, Fid.vnode,
4034                               pExtent->FileOffset.HighPart,
4035                               pExtent->FileOffset.LowPart);
4036                     osi_Log2(afsd_logp, "... coffset 0x%x:%x IN_USE by file system",
4037                               pExtent->CacheOffset.HighPart,
4038                               pExtent->CacheOffset.LowPart);
4039
4040                     /* Move the buffer to the front of the queue */
4041                     lock_ObtainWrite(&buf_globalLock);
4042                     buf_MoveToHeadOfRedirQueue(scp, bufp);
4043                     lock_ReleaseWrite(&buf_globalLock);
4044                     buf_Release(bufp);
4045                     continue;
4046                 }
4047
4048                 if (bufp->datap - RDR_extentBaseAddress == pExtent->CacheOffset.QuadPart) {
4049                     if (!(bufp->qFlags & CM_BUF_QREDIR)) {
4050                         osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4051                                  Fid.volume, Fid.vnode,
4052                                  pExtent->FileOffset.HighPart,
4053                                  pExtent->FileOffset.LowPart);
4054                         osi_Log2(afsd_logp, "... coffset 0x%x:%x not held by file system",
4055                                  pExtent->CacheOffset.HighPart,
4056                                  pExtent->CacheOffset.LowPart);
4057 #ifdef ODS_DEBUG
4058                         snprintf(dbgstr, 1024,
4059                                   "RDR_ProcessReleaseFileExtentsResult not held by redirector! flags 0x%x:%x vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4060                                   ReleaseFileExtentsResultCB->Flags, pExtent->Flags,
4061                                   Fid.volume, Fid.vnode, Fid.unique,
4062                                   pExtent->FileOffset.HighPart,
4063                                   pExtent->FileOffset.LowPart,
4064                                   pExtent->CacheOffset.HighPart,
4065                                   pExtent->CacheOffset.LowPart);
4066                         OutputDebugStringA( dbgstr);
4067 #endif
4068                     } else {
4069                         osi_Log5(afsd_logp, "RDR_ProcessReleaseFileExtentsResult bufp 0x%p foffset 0x%x:%x coffset 0x%x:%x",
4070                                  bufp, pExtent->FileOffset.HighPart, pExtent->FileOffset.LowPart,
4071                                  pExtent->CacheOffset.HighPart, pExtent->CacheOffset.LowPart);
4072
4073                         if (pExtent->Flags || ReleaseFileExtentsResultCB->Flags) {
4074                             lock_ObtainMutex(&bufp->mx);
4075                             if ( (ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_RELEASE) ||
4076                                  (pExtent->Flags & AFS_EXTENT_FLAG_RELEASE) )
4077                             {
4078                                 if (bufp->qFlags & CM_BUF_QREDIR) {
4079                                     lock_ObtainWrite(&buf_globalLock);
4080                                     if (bufp->qFlags & CM_BUF_QREDIR) {
4081                                         buf_RemoveFromRedirQueue(scp, bufp);
4082                                         buf_ReleaseLocked(bufp, TRUE);
4083                                     }
4084                                     lock_ReleaseWrite(&buf_globalLock);
4085                                 }
4086
4087 #ifdef ODS_DEBUG
4088                                 snprintf(dbgstr, 1024,
4089                                           "RDR_ProcessReleaseFileExtentsResult extent released: vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4090                                           Fid.volume, Fid.vnode, Fid.unique,
4091                                           pExtent->FileOffset.HighPart,
4092                                           pExtent->FileOffset.LowPart,
4093                                           pExtent->CacheOffset.HighPart,
4094                                           pExtent->CacheOffset.LowPart);
4095                                 OutputDebugStringA( dbgstr);
4096 #endif
4097
4098                                 released++;
4099                             } else {
4100                                 osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult not releasing vol 0x%x vno 0x%x foffset 0x%x:%x",
4101                                          Fid.volume, Fid.vnode,
4102                                          pExtent->FileOffset.HighPart,
4103                                          pExtent->FileOffset.LowPart);
4104                                 osi_Log2(afsd_logp, "... coffset 0x%x:%x",
4105                                          pExtent->CacheOffset.HighPart,
4106                                          pExtent->CacheOffset.LowPart);
4107 #ifdef ODS_DEBUG
4108                                 snprintf(dbgstr, 1024,
4109                                           "RDR_ProcessReleaseFileExtentsResult not released! vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4110                                           Fid.volume, Fid.vnode, Fid.unique,
4111                                           pExtent->FileOffset.HighPart,
4112                                           pExtent->FileOffset.LowPart,
4113                                           pExtent->CacheOffset.HighPart,
4114                                           pExtent->CacheOffset.LowPart);
4115                                 OutputDebugStringA( dbgstr);
4116 #endif
4117                             }
4118
4119                             if ((ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_DIRTY) ||
4120                                 (pExtent->Flags & AFS_EXTENT_FLAG_DIRTY))
4121                             {
4122 #ifdef VALIDATE_CHECK_SUM
4123                                 if ( buf_ValidateCheckSum(bufp) ) {
4124 #ifdef ODS_DEBUG
4125                                     HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
4126                                     if (ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_MD5_SET)
4127                                         HexCheckSum(md5dbg2, sizeof(md5dbg2), pExtent->MD5);
4128 #endif
4129                                     buf_ComputeCheckSum(bufp);
4130 #ifdef ODS_DEBUG
4131                                     HexCheckSum(md5dbg3, sizeof(md5dbg), bufp->md5cksum);
4132 #endif
4133                                     if (ReleaseFileExtentsResultCB->Flags & AFS_EXTENT_FLAG_MD5_SET)
4134                                     {
4135                                         if (memcmp(bufp->md5cksum, pExtent->MD5, 16))
4136                                         {
4137 #ifdef ODS_DEBUG
4138                                             snprintf(dbgstr, 1024,
4139                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set and checksums do not match! user %s kernel %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4140                                                       md5dbg3, md5dbg2,
4141                                                       Fid.volume, Fid.vnode, Fid.unique,
4142                                                       pExtent->FileOffset.HighPart,
4143                                                       pExtent->FileOffset.LowPart,
4144                                                       pExtent->CacheOffset.HighPart,
4145                                                       pExtent->CacheOffset.LowPart);
4146                                             OutputDebugStringA( dbgstr);
4147 #endif
4148                                             osi_Log4(afsd_logp,
4149                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set and checksums do not match! vol 0x%x vno 0x%x foffset 0x%x:%x",
4150                                                       Fid.volume, Fid.vnode,
4151                                                       pExtent->FileOffset.HighPart,
4152                                                       pExtent->FileOffset.LowPart);
4153                                             osi_Log2(afsd_logp,
4154                                                       "... coffset 0x%x:%x",
4155                                                       pExtent->CacheOffset.HighPart,
4156                                                       pExtent->CacheOffset.LowPart);
4157
4158                                             if (!deleted) {
4159                                                 buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
4160                                                 dirty++;
4161                                             }
4162                                         } else {
4163 #ifdef ODS_DEBUG
4164                                             snprintf(dbgstr, 1024,
4165                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set but extent has not changed! old %s kernel %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4166                                                       md5dbg, md5dbg2, md5dbg3,
4167                                                       Fid.volume, Fid.vnode, Fid.unique,
4168                                                       pExtent->FileOffset.HighPart,
4169                                                       pExtent->FileOffset.LowPart,
4170                                                       pExtent->CacheOffset.HighPart,
4171                                                       pExtent->CacheOffset.LowPart);
4172                                             OutputDebugStringA( dbgstr);
4173 #endif
4174                                             osi_Log4(afsd_logp,
4175                                                       "RDR_ProcessReleaseFileExtentsResult dirty flag set but extent has not changed vol 0x%x vno 0x%x foffset 0x%x:%x",
4176                                                       Fid.volume, Fid.vnode,
4177                                                       pExtent->FileOffset.HighPart,
4178                                                       pExtent->FileOffset.LowPart);
4179                                             osi_Log2(afsd_logp,
4180                                                       "... coffset 0x%x:%x",
4181                                                       pExtent->CacheOffset.HighPart,
4182                                                       pExtent->CacheOffset.LowPart);
4183                                         }
4184                                     }
4185                                 }
4186 #else /* !VALIDATE_CHECK_SUM */
4187                                 if (!deleted) {
4188                                     buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
4189                                     dirty++;
4190                                 }
4191 #ifdef ODS_DEBUG
4192                                 snprintf(dbgstr, 1024,
4193                                           "RDR_ProcessReleaseFileExtentsResult dirty! vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4194                                           Fid.volume, Fid.vnode, Fid.unique,
4195                                           pExtent->FileOffset.HighPart,
4196                                           pExtent->FileOffset.LowPart,
4197                                           pExtent->CacheOffset.HighPart,
4198                                           pExtent->CacheOffset.LowPart);
4199                                 OutputDebugStringA( dbgstr);
4200 #endif
4201 #endif /* VALIDATE_CHECK_SUM */
4202                             }
4203 #ifdef VALIDATE_CHECK_SUM
4204                             else {
4205 #ifdef ODS_DEBUG
4206                                 HexCheckSum(md5dbg, sizeof(md5dbg), bufp->md5cksum);
4207 #endif
4208                                 if (!buf_ValidateCheckSum(bufp) ) {
4209                                     buf_ComputeCheckSum(bufp);
4210 #ifdef ODS_DEBUG
4211                                     HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
4212                                     snprintf(dbgstr, 1024,
4213                                              "RDR_ProcessReleaseFileExtentsResult dirty flag not set but dirty! old %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4214                                              md5dbg, md5dbg3,
4215                                              Fid.volume, Fid.vnode, Fid.unique,
4216                                              pExtent->FileOffset.HighPart,
4217                                              pExtent->FileOffset.LowPart,
4218                                              pExtent->CacheOffset.HighPart,
4219                                              pExtent->CacheOffset.LowPart);
4220                                     OutputDebugStringA( dbgstr);
4221 #endif
4222                                     osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult dirty flag NOT set but extent has changed! vol 0x%x vno 0x%x foffset 0x%x:%x",
4223                                              Fid.volume, Fid.vnode,
4224                                              pExtent->FileOffset.HighPart,
4225                                              pExtent->FileOffset.LowPart);
4226                                     osi_Log2(afsd_logp, "... coffset 0x%x:%x",
4227                                              pExtent->CacheOffset.HighPart,
4228                                              pExtent->CacheOffset.LowPart);
4229
4230                                     if (!deleted) {
4231                                         buf_SetDirty(bufp, &req, pExtent->DirtyOffset, pExtent->DirtyLength, userp);
4232                                         dirty++;
4233                                     }
4234                                 } else {
4235                                     buf_ComputeCheckSum(bufp);
4236 #ifdef ODS_DEBUG
4237                                     HexCheckSum(md5dbg3, sizeof(md5dbg2), bufp->md5cksum);
4238                                     snprintf(dbgstr, 1024,
4239                                              "RDR_ProcessReleaseFileExtentsResult dirty flag not set and not dirty! old %s new %s vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4240                                              md5dbg, md5dbg3,
4241                                              Fid.volume, Fid.vnode, Fid.unique,
4242                                              pExtent->FileOffset.HighPart,
4243                                              pExtent->FileOffset.LowPart,
4244                                              pExtent->CacheOffset.HighPart,
4245                                              pExtent->CacheOffset.LowPart);
4246                                     OutputDebugStringA( dbgstr);
4247 #endif
4248                                 }
4249                             }
4250 #endif /* VALIDATE_CHECK_SUM */
4251                             lock_ReleaseMutex(&bufp->mx);
4252                         }
4253                     }
4254                 } else {
4255                     /* CacheOffset doesn't match bufp->datap */
4256                     char * datap = RDR_extentBaseAddress + pExtent->CacheOffset.QuadPart;
4257                     cm_buf_t *wbp;
4258
4259                     for (wbp = cm_data.buf_allp; wbp; wbp = wbp->allp) {
4260                         if (wbp->datap == datap)
4261                             break;
4262                     }
4263
4264 #ifdef ODS_DEBUG
4265                     snprintf(dbgstr, 1024,
4266                              "RDR_ProcessReleaseFileExtentsResult non-matching extent vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x flags 0x%x\n",
4267                              Fid.volume, Fid.vnode, Fid.unique,
4268                              pExtent->FileOffset.HighPart,
4269                              pExtent->FileOffset.LowPart,
4270                              pExtent->CacheOffset.HighPart,
4271                              pExtent->CacheOffset.LowPart,
4272                              pExtent->Flags);
4273                     OutputDebugStringA( dbgstr);
4274 #endif
4275                     osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult non-matching extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4276                              Fid.volume, Fid.vnode,
4277                              pExtent->FileOffset.HighPart,
4278                              pExtent->FileOffset.LowPart);
4279                     osi_Log3(afsd_logp, "... coffset 0x%x:%x flags 0x%x",
4280                              pExtent->CacheOffset.HighPart,
4281                              pExtent->CacheOffset.LowPart,
4282                              pExtent->Flags);
4283                     if (wbp)
4284                         osi_Log5(afsd_logp, "... coffset belongs to bp 0x%p vol 0x%x vno 0x%x foffset 0x%x:%x",
4285                                  wbp, wbp->fid.volume, wbp->fid.vnode, wbp->offset.HighPart, wbp->offset.LowPart);
4286                     else
4287                         osi_Log0(afsd_logp, "... coffset cannot be found");
4288                 }
4289                 buf_Release(bufp);
4290             } else {
4291                 if (pExtent->Flags & AFS_EXTENT_FLAG_UNKNOWN) {
4292                     osi_Log4(afsd_logp, "RDR_ReleaseFileExtentsResult extent vol 0x%x vno 0x%x foffset 0x%x:%x",
4293                              Fid.volume, Fid.vnode, pExtent->FileOffset.HighPart,
4294                              pExtent->FileOffset.LowPart);
4295                     osi_Log2(afsd_logp, "... coffset 0x%x:%x UNKNOWN to redirector; cm_buf not found -- recycled?",
4296                              pExtent->CacheOffset.HighPart,
4297                              pExtent->CacheOffset.LowPart);
4298
4299                     continue;
4300                 }
4301
4302 #ifdef ODS_DEBUG
4303                 snprintf(dbgstr, 1024,
4304                          "RDR_ProcessReleaseFileExtentsResult buf not found vol 0x%x vno 0x%x uniq 0x%x foffset 0x%x:%x coffset 0x%x:%x\n",
4305                          Fid.volume, Fid.vnode, Fid.unique,
4306                          pExtent->FileOffset.HighPart,
4307                          pExtent->FileOffset.LowPart,
4308                          pExtent->CacheOffset.HighPart,
4309                          pExtent->CacheOffset.LowPart);
4310                 OutputDebugStringA( dbgstr);
4311 #endif
4312                 osi_Log4(afsd_logp, "RDR_ProcessReleaseFileExtentsResult buf not found vol 0x%x vno 0x%x foffset 0x%x:%x",
4313                          Fid.volume, Fid.vnode,
4314                          pExtent->FileOffset.HighPart,
4315                          pExtent->FileOffset.LowPart);
4316                 osi_Log2(afsd_logp, "... coffset 0x%x:%x",
4317                          pExtent->CacheOffset.HighPart,
4318                          pExtent->CacheOffset.LowPart);
4319             }
4320         }
4321
4322         if (scp && dirty) {
4323             osi_hyper_t offset = {0,0};
4324             afs_uint32  length = 0;
4325
4326             /*
4327              * there is at least one dirty extent on this file.  queue up background store
4328              * requests for contiguous blocks
4329              */
4330             for ( extentno = 0; extentno < pFileCB->ExtentCount; extentno++ ) {
4331                 AFSFileExtentCB *pExtent = &pFileCB->FileExtents[extentno];
4332                 if (pExtent->FileOffset.QuadPart == offset.QuadPart + length &&
4333                      length < cm_chunkSize) {
4334                     length += cm_data.buf_blockSize;
4335                 } else {
4336                     if (!(offset.QuadPart == 0 && length == 0))
4337                         cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
4338                                             length, 0, userp, &req);
4339                     offset.QuadPart = pExtent->FileOffset.QuadPart;
4340                     length = cm_data.buf_blockSize;
4341                 }
4342             }
4343             cm_QueueBKGRequest(scp, cm_BkgStore, offset.LowPart, offset.HighPart,
4344                                 length, 0, userp, &req);
4345         }
4346
4347         osi_Log5(afsd_logp, "RDR_ProcessReleaseFileExtentsResult File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x Released %d",
4348                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique, released);
4349
4350       cleanup_file:
4351         if (userp)
4352             cm_ReleaseUser(userp);
4353         if (scp)
4354             cm_ReleaseSCache(scp);
4355
4356         p = (char *)pFileCB;
4357         p += sizeof(AFSReleaseFileExtentsResultFileCB);
4358         p += sizeof(AFSFileExtentCB) * (pFileCB->ExtentCount - 1);
4359         pNextFileCB = (AFSReleaseFileExtentsResultFileCB *)p;
4360     }
4361
4362     if (total_extents == 0) {
4363         osi_Log0(afsd_logp, "RDR_ProcessReleaseFileExtentsResult is empty");
4364         code = CM_ERROR_RETRY;
4365     }
4366
4367     if (code)
4368         osi_Log1(afsd_logp, "RDR_ProcessReleaseFileExtentsResult FAILURE code=0x%x", code);
4369     else
4370         osi_Log1(afsd_logp, "RDR_ProcessReleaseFileExtentsResult DONE code=0x%x", code);
4371
4372     return code;
4373 }
4374
4375 DWORD
4376 RDR_ReleaseFailedSetFileExtents( IN cm_user_t *userp,
4377                                  IN AFSSetFileExtentsCB *SetFileExtentsResultCB,
4378                                  IN DWORD ResultBufferLength)
4379 {
4380     afs_uint32  code = 0;
4381     cm_req_t    req;
4382     unsigned int extentno;
4383     cm_fid_t         Fid;
4384     cm_scache_t *    scp = NULL;
4385     int              dirty = 0;
4386
4387     RDR_InitReq(&req, FALSE);
4388
4389     osi_Log4(afsd_logp, "RDR_ReleaseFailedSetFileExtents %d.%d.%d.%d",
4390               SetFileExtentsResultCB->FileId.Cell, SetFileExtentsResultCB->FileId.Volume,
4391               SetFileExtentsResultCB->FileId.Vnode, SetFileExtentsResultCB->FileId.Unique);
4392
4393     /* Process the release */
4394     Fid.cell = SetFileExtentsResultCB->FileId.Cell;
4395     Fid.volume = SetFileExtentsResultCB->FileId.Volume;
4396     Fid.vnode = SetFileExtentsResultCB->FileId.Vnode;
4397     Fid.unique = SetFileExtentsResultCB->FileId.Unique;
4398     Fid.hash = SetFileExtentsResultCB->FileId.Hash;
4399
4400     if (Fid.cell == 0) {
4401         osi_Log4(afsd_logp, "RDR_ReleaseFailedSetFile Invalid FID %d.%d.%d.%d",
4402                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
4403         code = CM_ERROR_INVAL;
4404         goto cleanup_file;
4405     }
4406
4407     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4408     if (code) {
4409         osi_Log1(afsd_logp, "RDR_ReleaseFailedSetFileExtents cm_GetSCache FID failure code=0x%x",
4410                   code);
4411         /* Failure to find the cm_scache object cannot block return of the extents */
4412     }
4413
4414     for ( extentno = 0; extentno < SetFileExtentsResultCB->ExtentCount; extentno++ ) {
4415         osi_hyper_t thyper;
4416         cm_buf_t    *bufp;
4417         AFSFileExtentCB *pExtent = &SetFileExtentsResultCB->FileExtents[extentno];
4418
4419         thyper.QuadPart = pExtent->FileOffset.QuadPart;
4420
4421         bufp = buf_Find(&Fid, &thyper);
4422         if (bufp) {
4423             osi_Log5(afsd_logp, "RDR_ReleaseFailedSetFileExtents bufp 0x%p foffset 0x%x:%x coffset 0x%x:%x",
4424                       bufp, pExtent->FileOffset.HighPart, pExtent->FileOffset.LowPart,
4425                       pExtent->CacheOffset.HighPart, pExtent->CacheOffset.LowPart);
4426
4427             lock_ObtainMutex(&bufp->mx);
4428             if (bufp->qFlags & CM_BUF_QREDIR) {
4429                 lock_ObtainWrite(&buf_globalLock);
4430                 if (bufp->qFlags & CM_BUF_QREDIR) {
4431                     buf_RemoveFromRedirQueue(scp, bufp);
4432                     buf_ReleaseLocked(bufp, TRUE);
4433                 }
4434                 lock_ReleaseWrite(&buf_globalLock);
4435             }
4436             lock_ReleaseMutex(&bufp->mx);
4437             buf_Release(bufp);
4438         }
4439     }
4440
4441   cleanup_file:
4442     if (userp)
4443         cm_ReleaseUser(userp);
4444     if (scp)
4445         cm_ReleaseSCache(scp);
4446
4447     osi_Log1(afsd_logp, "RDR_ReleaseFailedSetFileExtents DONE code=0x%x", code);
4448     return code;
4449 }
4450
4451 void
4452 RDR_PioctlOpen( IN cm_user_t *userp,
4453                 IN AFSFileID  ParentId,
4454                 IN AFSPIOCtlOpenCloseRequestCB *pPioctlCB,
4455                 IN BOOL bWow64,
4456                 IN DWORD ResultBufferLength,
4457                 IN OUT AFSCommResult **ResultCB)
4458 {
4459     cm_fid_t    ParentFid;
4460     cm_fid_t    RootFid;
4461     cm_req_t    req;
4462
4463     RDR_InitReq(&req, bWow64);
4464
4465     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
4466     if (!(*ResultCB))
4467         return;
4468
4469     memset( *ResultCB,
4470             '\0',
4471             sizeof( AFSCommResult));
4472
4473     /* Get the active directory */
4474     ParentFid.cell = ParentId.Cell;
4475     ParentFid.volume = ParentId.Volume;
4476     ParentFid.vnode = ParentId.Vnode;
4477     ParentFid.unique = ParentId.Unique;
4478     ParentFid.hash = ParentId.Hash;
4479
4480     /* Get the root directory */
4481     RootFid.cell = pPioctlCB->RootId.Cell;
4482     RootFid.volume = pPioctlCB->RootId.Volume;
4483     RootFid.vnode = pPioctlCB->RootId.Vnode;
4484     RootFid.unique = pPioctlCB->RootId.Unique;
4485     RootFid.hash = pPioctlCB->RootId.Hash;
4486
4487     /* Create the pioctl index */
4488     RDR_SetupIoctl(pPioctlCB->RequestId, &ParentFid, &RootFid, userp, &req);
4489
4490     return;
4491 }
4492
4493
4494 void
4495 RDR_PioctlClose( IN cm_user_t *userp,
4496                  IN AFSFileID  ParentId,
4497                  IN AFSPIOCtlOpenCloseRequestCB *pPioctlCB,
4498                  IN BOOL bWow64,
4499                  IN DWORD ResultBufferLength,
4500                  IN OUT AFSCommResult **ResultCB)
4501 {
4502     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
4503     if (!(*ResultCB))
4504         return;
4505
4506     memset( *ResultCB,
4507             '\0',
4508             sizeof( AFSCommResult));
4509
4510     /* Cleanup the pioctl index */
4511     RDR_CleanupIoctl(pPioctlCB->RequestId);
4512
4513     return;
4514 }
4515
4516
4517 void
4518 RDR_PioctlWrite( IN cm_user_t *userp,
4519                  IN AFSFileID  ParentId,
4520                  IN AFSPIOCtlIORequestCB *pPioctlCB,
4521                  IN BOOL bWow64,
4522                  IN DWORD ResultBufferLength,
4523                  IN OUT AFSCommResult **ResultCB)
4524 {
4525     AFSPIOCtlIOResultCB *pResultCB;
4526     cm_scache_t *dscp = NULL;
4527     afs_uint32  code;
4528     cm_req_t    req;
4529     DWORD       status;
4530
4531     RDR_InitReq(&req, bWow64);
4532
4533     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4534     if (!(*ResultCB))
4535         return;
4536
4537     memset( *ResultCB,
4538             '\0',
4539             sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4540
4541     pResultCB = (AFSPIOCtlIOResultCB *)(*ResultCB)->ResultData;
4542
4543     code = RDR_IoctlWrite(userp, pPioctlCB->RequestId, pPioctlCB->BufferLength, pPioctlCB->MappedBuffer);
4544     if (code) {
4545         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4546         (*ResultCB)->ResultStatus = status;
4547         return;
4548     }
4549
4550     pResultCB->BytesProcessed = pPioctlCB->BufferLength;
4551     (*ResultCB)->ResultBufferLength = sizeof( AFSPIOCtlIOResultCB);
4552 }
4553
4554 void
4555 RDR_PioctlRead( IN cm_user_t *userp,
4556                 IN AFSFileID  ParentId,
4557                 IN AFSPIOCtlIORequestCB *pPioctlCB,
4558                 IN BOOL bWow64,
4559                 IN BOOL bIsLocalSystem,
4560                 IN DWORD ResultBufferLength,
4561                 IN OUT AFSCommResult **ResultCB)
4562 {
4563     AFSPIOCtlIOResultCB *pResultCB;
4564     cm_scache_t *dscp = NULL;
4565     afs_uint32  code;
4566     cm_req_t    req;
4567     DWORD       status;
4568     afs_uint32  pflags = (bIsLocalSystem ? AFSCALL_FLAG_LOCAL_SYSTEM : 0);
4569
4570     RDR_InitReq(&req, bWow64);
4571
4572     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4573     if (!(*ResultCB))
4574         return;
4575
4576     memset( *ResultCB,
4577             '\0',
4578             sizeof( AFSCommResult) + sizeof(AFSPIOCtlIOResultCB));
4579
4580     pResultCB = (AFSPIOCtlIOResultCB *)(*ResultCB)->ResultData;
4581
4582     code = RDR_IoctlRead(userp, pPioctlCB->RequestId, pPioctlCB->BufferLength, pPioctlCB->MappedBuffer,
4583                          &pResultCB->BytesProcessed, pflags);
4584     if (code) {
4585         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4586         (*ResultCB)->ResultStatus = status;
4587         return;
4588     }
4589
4590     (*ResultCB)->ResultBufferLength = sizeof( AFSPIOCtlIOResultCB);
4591 }
4592
4593 void
4594 RDR_ByteRangeLockSync( IN cm_user_t     *userp,
4595                        IN AFSFileID     FileId,
4596                        IN AFSByteRangeLockRequestCB *pBRLRequestCB,
4597                        IN BOOL bWow64,
4598                        IN DWORD ResultBufferLength,
4599                        IN OUT AFSCommResult **ResultCB)
4600 {
4601     AFSByteRangeLockResultCB *pResultCB = NULL;
4602     LARGE_INTEGER ProcessId;
4603     DWORD       Length;
4604     cm_scache_t *scp = NULL;
4605     cm_fid_t    Fid;
4606     afs_uint32  code;
4607     cm_req_t    req;
4608     cm_key_t    key;
4609     DWORD       i;
4610     DWORD       status;
4611
4612     ProcessId.QuadPart = pBRLRequestCB->ProcessId;
4613
4614     RDR_InitReq(&req, bWow64);
4615
4616     osi_Log4(afsd_logp, "RDR_ByteRangeLockSync File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4617               FileId.Cell, FileId.Volume,
4618               FileId.Vnode, FileId.Unique);
4619     osi_Log2(afsd_logp, "... ProcessId 0x%x:%x",
4620              ProcessId.HighPart, ProcessId.LowPart);
4621
4622     Length = sizeof( AFSByteRangeLockResultCB) + ((pBRLRequestCB->Count - 1) * sizeof(AFSByteRangeLockResult));
4623     if (Length > ResultBufferLength) {
4624         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult));
4625         if (!(*ResultCB))
4626             return;
4627         memset( *ResultCB, 0, sizeof(AFSCommResult));
4628         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
4629         return;
4630     }
4631
4632     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
4633     if (!(*ResultCB))
4634         return;
4635     memset( *ResultCB, '\0', Length + sizeof( AFSCommResult) );
4636     (*ResultCB)->ResultBufferLength = Length;
4637
4638     pResultCB = (AFSByteRangeLockResultCB *)(*ResultCB)->ResultData;
4639     pResultCB->FileId = FileId;
4640     pResultCB->Count = pBRLRequestCB->Count;
4641
4642     /* Allocate the extents from the buffer package */
4643     Fid.cell = FileId.Cell;
4644     Fid.volume = FileId.Volume;
4645     Fid.vnode = FileId.Vnode;
4646     Fid.unique = FileId.Unique;
4647     Fid.hash = FileId.Hash;
4648
4649     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4650     if (code) {
4651         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4652         (*ResultCB)->ResultStatus = status;
4653         (*ResultCB)->ResultBufferLength = 0;
4654         osi_Log2(afsd_logp, "RDR_ByteRangeLockSync cm_GetSCache FID failure code=0x%x status=0x%x",
4655                   code, status);
4656         return;
4657     }
4658
4659     lock_ObtainWrite(&scp->rw);
4660
4661     /* start by looking up the file's end */
4662     code = cm_SyncOp(scp, NULL, userp, &req, 0,
4663                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4664     if (code) {
4665         lock_ReleaseWrite(&scp->rw);
4666         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4667         (*ResultCB)->ResultStatus = status;
4668         (*ResultCB)->ResultBufferLength = 0;
4669         osi_Log3(afsd_logp, "RDR_ByteRangeLockSync cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
4670                  scp, code, status);
4671         return;
4672     }
4673
4674     /* the scp is now locked and current */
4675     key = cm_GenerateKey(CM_SESSION_IFS, ProcessId.QuadPart, 0);
4676
4677     for ( i=0; i<pBRLRequestCB->Count; i++ ) {
4678         pResultCB->Result[i].LockType = pBRLRequestCB->Request[i].LockType;
4679         pResultCB->Result[i].Offset = pBRLRequestCB->Request[i].Offset;
4680         pResultCB->Result[i].Length = pBRLRequestCB->Request[i].Length;
4681
4682         code = cm_Lock(scp,
4683                        pBRLRequestCB->Request[i].LockType == AFS_BYTE_RANGE_LOCK_TYPE_SHARED,
4684                        pBRLRequestCB->Request[i].Offset,
4685                        pBRLRequestCB->Request[i].Length,
4686                        key, 0, userp, &req, NULL);
4687
4688         if (code) {
4689             osi_Log4(afsd_logp, "RDR_ByteRangeLockSync FAILURE code 0x%x type 0x%u offset 0x%x:%x",
4690                      code,
4691                      pBRLRequestCB->Request[i].LockType,
4692                      pBRLRequestCB->Request[i].Offset.HighPart,
4693                      pBRLRequestCB->Request[i].Offset.LowPart);
4694             osi_Log2(afsd_logp, "... length 0x%x:%x",
4695                      pBRLRequestCB->Request[i].Length.HighPart,
4696                      pBRLRequestCB->Request[i].Length.LowPart);
4697         }
4698
4699         switch (code) {
4700         case 0:
4701             pResultCB->Result[i].Status = 0;
4702             break;
4703         case CM_ERROR_WOULDBLOCK:
4704             pResultCB->Result[i].Status = STATUS_FILE_LOCK_CONFLICT;
4705             break;
4706         default:
4707             pResultCB->Result[i].Status = STATUS_LOCK_NOT_GRANTED;
4708         }
4709     }
4710
4711     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4712     lock_ReleaseWrite(&scp->rw);
4713     cm_ReleaseSCache(scp);
4714
4715     (*ResultCB)->ResultStatus = 0;
4716     osi_Log0(afsd_logp, "RDR_ByteRangeLockSync SUCCESS");
4717     return;
4718 }
4719
4720 void
4721 RDR_ByteRangeUnlock( IN cm_user_t     *userp,
4722                      IN AFSFileID     FileId,
4723                      IN AFSByteRangeUnlockRequestCB *pBRURequestCB,
4724                      IN BOOL bWow64,
4725                      IN DWORD ResultBufferLength,
4726                      IN OUT AFSCommResult **ResultCB)
4727 {
4728     AFSByteRangeUnlockResultCB *pResultCB = NULL;
4729     LARGE_INTEGER ProcessId;
4730     DWORD       Length;
4731     cm_scache_t *scp = NULL;
4732     cm_fid_t    Fid;
4733     afs_uint32  code;
4734     cm_req_t    req;
4735     cm_key_t    key;
4736     DWORD       i;
4737     DWORD       status;
4738
4739     ProcessId.QuadPart = pBRURequestCB->ProcessId;
4740
4741     RDR_InitReq(&req, bWow64);
4742
4743     osi_Log4(afsd_logp, "RDR_ByteRangeUnlock File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4744               FileId.Cell, FileId.Volume,
4745               FileId.Vnode, FileId.Unique);
4746     osi_Log2(afsd_logp, "... ProcessId 0x%x:%x",
4747              ProcessId.HighPart, ProcessId.LowPart);
4748
4749     Length = sizeof( AFSByteRangeUnlockResultCB) + ((pBRURequestCB->Count - 1) * sizeof(AFSByteRangeLockResult));
4750     if (Length > ResultBufferLength) {
4751         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult));
4752         if (!(*ResultCB))
4753             return;
4754         memset( *ResultCB, 0, sizeof(AFSCommResult));
4755         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
4756         return;
4757     }
4758
4759     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
4760     if (!(*ResultCB))
4761         return;
4762     memset( *ResultCB, '\0', Length + sizeof( AFSCommResult) );
4763     (*ResultCB)->ResultBufferLength = Length;
4764
4765     pResultCB = (AFSByteRangeUnlockResultCB *)(*ResultCB)->ResultData;
4766     pResultCB->Count = pBRURequestCB->Count;
4767
4768     /* Allocate the extents from the buffer package */
4769     Fid.cell = FileId.Cell;
4770     Fid.volume = FileId.Volume;
4771     Fid.vnode = FileId.Vnode;
4772     Fid.unique = FileId.Unique;
4773     Fid.hash = FileId.Hash;
4774
4775     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4776     if (code) {
4777         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4778         (*ResultCB)->ResultStatus = status;
4779         (*ResultCB)->ResultBufferLength = 0;
4780         osi_Log2(afsd_logp, "RDR_ByteRangeUnlock cm_GetSCache FID failure code=0x%x status=0x%x",
4781                   code, status);
4782         return;
4783     }
4784
4785     lock_ObtainWrite(&scp->rw);
4786
4787     /* start by looking up the file's end */
4788     code = cm_SyncOp(scp, NULL, userp, &req, 0,
4789                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4790     if (code) {
4791         lock_ReleaseWrite(&scp->rw);
4792         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4793         (*ResultCB)->ResultStatus = status;
4794         (*ResultCB)->ResultBufferLength = 0;
4795         osi_Log3(afsd_logp, "RDR_ByteRangeUnlock cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
4796                  scp, code, status);
4797         return;
4798     }
4799
4800     /* the scp is now locked and current */
4801     key = cm_GenerateKey(CM_SESSION_IFS, ProcessId.QuadPart, 0);
4802
4803     for ( i=0; i<pBRURequestCB->Count; i++ ) {
4804         pResultCB->Result[i].LockType = pBRURequestCB->Request[i].LockType;
4805         pResultCB->Result[i].Offset = pBRURequestCB->Request[i].Offset;
4806         pResultCB->Result[i].Length = pBRURequestCB->Request[i].Length;
4807
4808         code = cm_Unlock(scp,
4809                          pBRURequestCB->Request[i].LockType == AFS_BYTE_RANGE_LOCK_TYPE_SHARED,
4810                          pBRURequestCB->Request[i].Offset,
4811                          pBRURequestCB->Request[i].Length,
4812                          key, CM_UNLOCK_FLAG_MATCH_RANGE, userp, &req);
4813
4814         if (code) {
4815             osi_Log4(afsd_logp, "RDR_ByteRangeUnlock FAILURE code 0x%x type 0x%u offset 0x%x:%x",
4816                      code, pBRURequestCB->Request[i].LockType,
4817                      pBRURequestCB->Request[i].Offset.HighPart,
4818                      pBRURequestCB->Request[i].Offset.LowPart);
4819             osi_Log2(afsd_logp, "... length 0x%x:%x",
4820                      pBRURequestCB->Request[i].Length.HighPart,
4821                      pBRURequestCB->Request[i].Length.LowPart);
4822         }
4823         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4824         pResultCB->Result[i].Status = status;
4825     }
4826
4827     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4828     lock_ReleaseWrite(&scp->rw);
4829     cm_ReleaseSCache(scp);
4830
4831     (*ResultCB)->ResultStatus = 0;
4832     osi_Log0(afsd_logp, "RDR_ByteRangeUnlock SUCCESS");
4833     return;
4834 }
4835
4836 void
4837 RDR_ByteRangeUnlockAll( IN cm_user_t     *userp,
4838                         IN AFSFileID     FileId,
4839                         IN AFSByteRangeUnlockRequestCB *pBRURequestCB,
4840                         IN BOOL bWow64,
4841                         IN DWORD ResultBufferLength,
4842                         IN OUT AFSCommResult **ResultCB)
4843 {
4844     AFSByteRangeUnlockResultCB *pResultCB = NULL;
4845     LARGE_INTEGER ProcessId;
4846     cm_scache_t *scp = NULL;
4847     cm_fid_t    Fid;
4848     afs_uint32  code;
4849     cm_req_t    req;
4850     cm_key_t    key;
4851     DWORD       status;
4852
4853     ProcessId.QuadPart = pBRURequestCB->ProcessId;
4854
4855     RDR_InitReq(&req, bWow64);
4856
4857     osi_Log4(afsd_logp, "RDR_ByteRangeUnlockAll File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4858               FileId.Cell, FileId.Volume,
4859               FileId.Vnode, FileId.Unique);
4860     osi_Log2(afsd_logp, "... ProcessId 0x%x:%x",
4861              ProcessId.HighPart, ProcessId.LowPart);
4862
4863     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
4864     if (!(*ResultCB))
4865         return;
4866     memset( *ResultCB, '\0', sizeof( AFSCommResult));
4867     (*ResultCB)->ResultBufferLength = 0;
4868
4869     /* Allocate the extents from the buffer package */
4870     Fid.cell = FileId.Cell;
4871     Fid.volume = FileId.Volume;
4872     Fid.vnode = FileId.Vnode;
4873     Fid.unique = FileId.Unique;
4874     Fid.hash = FileId.Hash;
4875
4876     code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4877     if (code) {
4878         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4879         (*ResultCB)->ResultStatus = status;
4880         (*ResultCB)->ResultBufferLength = 0;
4881         osi_Log2(afsd_logp, "RDR_ByteRangeUnlockAll cm_GetSCache FID failure code=0x%x status=0x%x",
4882                   code, status);
4883         return;
4884     }
4885
4886     lock_ObtainWrite(&scp->rw);
4887
4888     /* start by looking up the file's end */
4889     code = cm_SyncOp(scp, NULL, userp, &req, 0,
4890                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4891     if (code) {
4892         lock_ReleaseWrite(&scp->rw);
4893         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4894         (*ResultCB)->ResultStatus = status;
4895         (*ResultCB)->ResultBufferLength = 0;
4896         osi_Log3(afsd_logp, "RDR_ByteRangeUnlockAll cm_SyncOp failure scp=0x%p code=0x%x status=0x%x",
4897                  scp, code, status);
4898         return;
4899     }
4900
4901     /* the scp is now locked and current */
4902     key = cm_GenerateKey(CM_SESSION_IFS, ProcessId.QuadPart, 0);
4903
4904     code = cm_UnlockByKey(scp, key, 0, userp, &req);
4905
4906     cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS | CM_SCACHESYNC_LOCK);
4907     lock_ReleaseWrite(&scp->rw);
4908     cm_ReleaseSCache(scp);
4909
4910     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4911     (*ResultCB)->ResultStatus = status;
4912
4913     if (code)
4914         osi_Log1(afsd_logp, "RDR_ByteRangeUnlockAll FAILURE code 0x%x", code);
4915     else
4916         osi_Log0(afsd_logp, "RDR_ByteRangeUnlockAll SUCCESS");
4917     return;
4918
4919 }
4920
4921 void
4922 RDR_GetVolumeInfo( IN cm_user_t     *userp,
4923                    IN AFSFileID     FileId,
4924                    IN BOOL bWow64,
4925                    IN DWORD ResultBufferLength,
4926                    IN OUT AFSCommResult **ResultCB)
4927 {
4928     AFSVolumeInfoCB *pResultCB = NULL;
4929     DWORD       Length;
4930     cm_scache_t *scp = NULL;
4931     cm_volume_t *volp = NULL;
4932     afs_uint32   volType;
4933     cm_cell_t   *cellp = NULL;
4934     cm_fid_t    Fid;
4935     afs_uint32  code;
4936     cm_req_t    req;
4937     DWORD       status;
4938     FILETIME ft = {0x832cf000, 0x01abfcc4}; /* October 1, 1982 00:00:00 +0600 */
4939
4940     char volName[32]="(unknown)";
4941     char offLineMsg[256]="server temporarily inaccessible";
4942     char motd[256]="server temporarily inaccessible";
4943     cm_conn_t *connp;
4944     AFSFetchVolumeStatus volStat;
4945     char *Name;
4946     char *OfflineMsg;
4947     char *MOTD;
4948     struct rx_connection * rxconnp;
4949     int sync_done = 0;
4950     int scp_locked = 0;
4951
4952     RDR_InitReq(&req, bWow64);
4953
4954     osi_Log4(afsd_logp, "RDR_GetVolumeInfo File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
4955              FileId.Cell, FileId.Volume,
4956              FileId.Vnode, FileId.Unique);
4957
4958     Length = sizeof( AFSCommResult) + sizeof(AFSVolumeInfoCB);
4959     if (sizeof(AFSVolumeInfoCB) > ResultBufferLength) {
4960         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
4961         if (!(*ResultCB))
4962             return;
4963         memset( *ResultCB, 0, sizeof(AFSCommResult));
4964         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
4965         return;
4966     }
4967
4968     *ResultCB = (AFSCommResult *)malloc( Length );
4969     if (!(*ResultCB))
4970         return;
4971     memset( *ResultCB, '\0', Length );
4972     (*ResultCB)->ResultBufferLength = sizeof(AFSVolumeInfoCB);
4973     pResultCB = (AFSVolumeInfoCB *)(*ResultCB)->ResultData;
4974
4975     if (FileId.Cell != 0) {
4976         cm_SetFid(&Fid, FileId.Cell, FileId.Volume, 1, 1);
4977         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
4978         if (code) {
4979             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
4980             (*ResultCB)->ResultStatus = status;
4981             (*ResultCB)->ResultBufferLength = 0;
4982             osi_Log2(afsd_logp, "RDR_GetVolumeInfo cm_GetSCache FID failure code=0x%x status=0x%x",
4983                       code, status);
4984             return;
4985         }
4986     } else {
4987         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
4988         osi_Log0(afsd_logp, "RDR_GetVolumeInfo Object Name Invalid - Cell = 0");
4989         return;
4990     }
4991     lock_ObtainWrite(&scp->rw);
4992     scp_locked = 1;
4993
4994     pResultCB->SectorsPerAllocationUnit = 1;
4995     pResultCB->BytesPerSector = 1024;
4996
4997     pResultCB->CellID = scp->fid.cell;
4998     pResultCB->VolumeID = scp->fid.volume;
4999     pResultCB->Characteristics = FILE_REMOTE_DEVICE;
5000     pResultCB->FileSystemAttributes = FILE_CASE_PRESERVED_NAMES | FILE_UNICODE_ON_DISK |
5001         FILE_SUPPORTS_REPARSE_POINTS;
5002
5003     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
5004          scp->fid.volume==AFS_FAKE_ROOT_VOL_ID)
5005     {
5006         pResultCB->TotalAllocationUnits.QuadPart = 100;
5007         memcpy(&pResultCB->VolumeCreationTime, &ft, sizeof(ft));
5008
5009         pResultCB->AvailableAllocationUnits.QuadPart = 0;
5010         pResultCB->Characteristics |= FILE_READ_ONLY_DEVICE;
5011
5012         pResultCB->VolumeLabelLength = cm_Utf8ToUtf16( "Freelance.Local.Root", -1, pResultCB->VolumeLabel,
5013                                                        (sizeof(pResultCB->VolumeLabel) / sizeof(WCHAR)) + 1);
5014         if ( pResultCB->VolumeLabelLength )
5015             pResultCB->VolumeLabelLength--;
5016     } else {
5017         memcpy(&pResultCB->VolumeCreationTime, &ft, sizeof(ft));
5018
5019         volp = cm_GetVolumeByFID(&scp->fid);
5020         if (!volp) {
5021             code = CM_ERROR_NOSUCHVOLUME;
5022             goto _done;
5023         }
5024         volType = cm_VolumeType(volp, scp->fid.volume);
5025
5026         pResultCB->Characteristics |= ((volType == ROVOL || volType == BACKVOL) ? FILE_READ_ONLY_DEVICE : 0);
5027
5028         code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
5029                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5030         if (code == 0)
5031         {
5032             sync_done = 1;
5033
5034             Name = volName;
5035             OfflineMsg = offLineMsg;
5036             MOTD = motd;
5037             lock_ReleaseWrite(&scp->rw);
5038             scp_locked = 0;
5039
5040             do {
5041                 code = cm_ConnFromFID(&scp->fid, userp, &req, &connp);
5042                 if (code) continue;
5043
5044                 rxconnp = cm_GetRxConn(connp);
5045                 code = RXAFS_GetVolumeStatus(rxconnp, scp->fid.volume,
5046                                               &volStat, &Name, &OfflineMsg, &MOTD);
5047                 rx_PutConnection(rxconnp);
5048
5049             } while (cm_Analyze(connp, userp, &req, &scp->fid, NULL, 0, NULL, NULL, NULL, code));
5050             code = cm_MapRPCError(code, &req);
5051         }
5052
5053         if (code == 0) {
5054             if (volStat.MaxQuota)
5055             {
5056                 pResultCB->TotalAllocationUnits.QuadPart = volStat.MaxQuota;
5057                 if (volType == ROVOL || volType == BACKVOL) {
5058                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5059                 }
5060                 else
5061                 {
5062                     pResultCB->AvailableAllocationUnits.QuadPart =
5063                         min(volStat.MaxQuota - volStat.BlocksInUse, volStat.PartBlocksAvail);
5064                 }
5065             }
5066             else
5067             {
5068                 pResultCB->TotalAllocationUnits.QuadPart = volStat.PartMaxBlocks;
5069                 if (volType == ROVOL || volType == BACKVOL) {
5070                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5071                 }
5072                 else
5073                 {
5074                     pResultCB->AvailableAllocationUnits.QuadPart = volStat.PartBlocksAvail;
5075                 }
5076             }
5077         } else {
5078             /*
5079              * Lie about the available space.  Out of quota errors will need
5080              * detected when the file server rejects the store data.
5081              */
5082             pResultCB->TotalAllocationUnits.QuadPart = 0x7FFFFFFF;
5083             pResultCB->AvailableAllocationUnits.QuadPart = (volType == ROVOL || volType == BACKVOL) ? 0 : 0x3F000000;
5084             code = 0;
5085         }
5086
5087         pResultCB->VolumeLabelLength = cm_Utf8ToUtf16( volp->namep, -1, pResultCB->VolumeLabel,
5088                                                        (sizeof(pResultCB->VolumeLabel) / sizeof(WCHAR)) + 1);
5089         if ( pResultCB->VolumeLabelLength )
5090             pResultCB->VolumeLabelLength--;
5091
5092         if (sync_done) {
5093             if (!scp_locked) {
5094                 lock_ObtainWrite(&scp->rw);
5095                 scp_locked = 1;
5096             }
5097             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5098         }
5099     }
5100     pResultCB->VolumeLabelLength *= sizeof(WCHAR);  /* convert to bytes from chars */
5101
5102   _done:
5103     if (scp_locked)
5104         lock_ReleaseWrite(&scp->rw);
5105     if (volp)
5106        cm_PutVolume(volp);
5107     cm_ReleaseSCache(scp);
5108
5109     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5110     (*ResultCB)->ResultStatus = status;
5111     osi_Log0(afsd_logp, "RDR_GetVolumeInfo SUCCESS");
5112     return;
5113 }
5114
5115 void
5116 RDR_GetVolumeSizeInfo( IN cm_user_t     *userp,
5117                    IN AFSFileID     FileId,
5118                    IN BOOL bWow64,
5119                    IN DWORD ResultBufferLength,
5120                    IN OUT AFSCommResult **ResultCB)
5121 {
5122     AFSVolumeSizeInfoCB *pResultCB = NULL;
5123     DWORD       Length;
5124     cm_scache_t *scp = NULL;
5125     cm_volume_t *volp = NULL;
5126     afs_uint32   volType;
5127     cm_cell_t   *cellp = NULL;
5128     cm_fid_t    Fid;
5129     afs_uint32  code;
5130     cm_req_t    req;
5131     DWORD       status;
5132
5133     char volName[32]="(unknown)";
5134     char offLineMsg[256]="server temporarily inaccessible";
5135     char motd[256]="server temporarily inaccessible";
5136     cm_conn_t *connp;
5137     AFSFetchVolumeStatus volStat;
5138     char *Name;
5139     char *OfflineMsg;
5140     char *MOTD;
5141     struct rx_connection * rxconnp;
5142     int sync_done = 0;
5143     int scp_locked = 0;
5144
5145     RDR_InitReq(&req, bWow64);
5146
5147     osi_Log4(afsd_logp, "RDR_GetVolumeSizeInfo File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
5148              FileId.Cell, FileId.Volume,
5149              FileId.Vnode, FileId.Unique);
5150
5151     Length = sizeof( AFSCommResult) + sizeof(AFSVolumeSizeInfoCB);
5152     if (sizeof(AFSVolumeSizeInfoCB) > ResultBufferLength) {
5153         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
5154         if (!(*ResultCB))
5155             return;
5156         memset( *ResultCB, 0, sizeof(AFSCommResult));
5157         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
5158         return;
5159     }
5160
5161     *ResultCB = (AFSCommResult *)malloc( Length );
5162     if (!(*ResultCB))
5163         return;
5164     memset( *ResultCB, '\0', Length );
5165     (*ResultCB)->ResultBufferLength = sizeof(AFSVolumeSizeInfoCB);
5166     pResultCB = (AFSVolumeSizeInfoCB *)(*ResultCB)->ResultData;
5167
5168     if (FileId.Cell != 0) {
5169         cm_SetFid(&Fid, FileId.Cell, FileId.Volume, 1, 1);
5170         code = cm_GetSCache(&Fid, NULL, &scp, userp, &req);
5171         if (code) {
5172             smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5173             (*ResultCB)->ResultStatus = status;
5174             (*ResultCB)->ResultBufferLength = 0;
5175             osi_Log2(afsd_logp, "RDR_GetVolumeSizeInfo cm_GetSCache FID failure code=0x%x status=0x%x",
5176                       code, status);
5177             return;
5178         }
5179     } else {
5180         (*ResultCB)->ResultStatus = STATUS_OBJECT_NAME_INVALID;
5181         osi_Log0(afsd_logp, "RDR_GetVolumeSizeInfo Object Name Invalid - Cell = 0");
5182         return;
5183     }
5184     lock_ObtainWrite(&scp->rw);
5185     scp_locked = 1;
5186
5187     pResultCB->SectorsPerAllocationUnit = 1;
5188     pResultCB->BytesPerSector = 1024;
5189
5190     if (scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
5191         scp->fid.volume==AFS_FAKE_ROOT_VOL_ID)
5192     {
5193         pResultCB->TotalAllocationUnits.QuadPart = 100;
5194         pResultCB->AvailableAllocationUnits.QuadPart = 0;
5195     } else {
5196         volp = cm_GetVolumeByFID(&scp->fid);
5197         if (!volp) {
5198             code = CM_ERROR_NOSUCHVOLUME;
5199             goto _done;
5200         }
5201
5202         volType = cm_VolumeType(volp, scp->fid.volume);
5203
5204         code = cm_SyncOp(scp, NULL, userp, &req, PRSFS_READ,
5205                          CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5206         if (code == 0)
5207         {
5208             sync_done = 1;
5209
5210             Name = volName;
5211             OfflineMsg = offLineMsg;
5212             MOTD = motd;
5213             lock_ReleaseWrite(&scp->rw);
5214             scp_locked = 0;
5215
5216             do {
5217                 code = cm_ConnFromFID(&scp->fid, userp, &req, &connp);
5218                 if (code) continue;
5219
5220                 rxconnp = cm_GetRxConn(connp);
5221                 code = RXAFS_GetVolumeStatus(rxconnp, scp->fid.volume,
5222                                               &volStat, &Name, &OfflineMsg, &MOTD);
5223                 rx_PutConnection(rxconnp);
5224
5225             } while (cm_Analyze(connp, userp, &req, &scp->fid, NULL, 0, NULL, NULL, NULL, code));
5226             code = cm_MapRPCError(code, &req);
5227         }
5228
5229         if (code == 0) {
5230             if (volStat.MaxQuota)
5231             {
5232                 pResultCB->TotalAllocationUnits.QuadPart = volStat.MaxQuota;
5233                 if (volType == ROVOL || volType == BACKVOL) {
5234                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5235                 }
5236                 else
5237                 {
5238                     pResultCB->AvailableAllocationUnits.QuadPart =
5239                         min(volStat.MaxQuota - volStat.BlocksInUse, volStat.PartBlocksAvail);
5240                 }
5241             }
5242             else
5243             {
5244                 pResultCB->TotalAllocationUnits.QuadPart = volStat.PartMaxBlocks;
5245                 if (volType == ROVOL || volType == BACKVOL) {
5246                     pResultCB->AvailableAllocationUnits.QuadPart = 0;
5247                 }
5248                 else
5249                 {
5250                     pResultCB->AvailableAllocationUnits.QuadPart = volStat.PartBlocksAvail;
5251                 }
5252             }
5253         } else {
5254             /*
5255              * Lie about the available space.  Out of quota errors will need
5256              * detected when the file server rejects the store data.
5257              */
5258             pResultCB->TotalAllocationUnits.QuadPart = 0x7FFFFFFF;
5259             pResultCB->AvailableAllocationUnits.QuadPart = (volType == ROVOL || volType == BACKVOL) ? 0 : 0x3F000000;
5260             code = 0;
5261         }
5262
5263         if (sync_done) {
5264             if (!scp_locked) {
5265                 lock_ObtainWrite(&scp->rw);
5266                 scp_locked = 1;
5267             }
5268             cm_SyncOpDone(scp, NULL, CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
5269         }
5270     }
5271
5272   _done:
5273     if (scp_locked)
5274         lock_ReleaseWrite(&scp->rw);
5275     if (volp)
5276        cm_PutVolume(volp);
5277     cm_ReleaseSCache(scp);
5278
5279     smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5280     (*ResultCB)->ResultStatus = status;
5281     osi_Log0(afsd_logp, "RDR_GetVolumeSizeInfo SUCCESS");
5282     return;
5283 }
5284
5285 void
5286 RDR_HoldFid( IN cm_user_t     *userp,
5287              IN AFSHoldFidRequestCB * pHoldFidCB,
5288              IN BOOL bFast,
5289              IN DWORD ResultBufferLength,
5290              IN OUT AFSCommResult **ResultCB)
5291 {
5292     AFSHoldFidResultCB *pResultCB = NULL;
5293     DWORD       index;
5294     DWORD       Length;
5295     cm_req_t    req;
5296
5297     RDR_InitReq(&req, FALSE);
5298
5299     osi_Log1(afsd_logp, "RDR_HoldFid Count=%u", pHoldFidCB->Count);
5300
5301     Length = sizeof(AFSHoldFidResultCB) + (pHoldFidCB->Count-1) * sizeof(AFSFidResult);
5302     if (Length > ResultBufferLength) {
5303         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
5304         if (!(*ResultCB))
5305             return;
5306         memset( *ResultCB, 0, sizeof(AFSCommResult));
5307         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
5308         return;
5309     }
5310     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
5311     if (!(*ResultCB))
5312         return;
5313     memset( *ResultCB, '\0', Length );
5314     (*ResultCB)->ResultBufferLength = Length;
5315     pResultCB = (AFSHoldFidResultCB *)(*ResultCB)->ResultData;
5316
5317     for ( index = 0; index < pHoldFidCB->Count; index++ )
5318     {
5319         cm_scache_t *scp = NULL;
5320         cm_fid_t    Fid;
5321
5322         Fid.cell   = pResultCB->Result[index].FileID.Cell   = pHoldFidCB->FileID[index].Cell;
5323         Fid.volume = pResultCB->Result[index].FileID.Volume = pHoldFidCB->FileID[index].Volume;
5324         Fid.vnode  = pResultCB->Result[index].FileID.Vnode  = pHoldFidCB->FileID[index].Vnode;
5325         Fid.unique = pResultCB->Result[index].FileID.Unique = pHoldFidCB->FileID[index].Unique;
5326         Fid.hash   = pResultCB->Result[index].FileID.Hash   = pHoldFidCB->FileID[index].Hash;
5327
5328         osi_Log4( afsd_logp,
5329                   "RDR_HoldFid File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
5330                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
5331
5332         scp = cm_FindSCache(&Fid);
5333         if (scp) {
5334             RDR_FlagScpInUse( scp, FALSE );
5335             cm_ReleaseSCache(scp);
5336         }
5337         pResultCB->Result[index].Status = 0;
5338     }
5339
5340     (*ResultCB)->ResultStatus = 0;
5341     osi_Log0(afsd_logp, "RDR_HoldFid SUCCESS");
5342     return;
5343 }
5344
5345 void
5346 RDR_ReleaseFid( IN cm_user_t     *userp,
5347                 IN AFSReleaseFidRequestCB * pReleaseFidCB,
5348                 IN BOOL bFast,
5349                 IN DWORD ResultBufferLength,
5350                 IN OUT AFSCommResult **ResultCB)
5351 {
5352     AFSReleaseFidResultCB *pResultCB = NULL;
5353     DWORD       index;
5354     DWORD       Length;
5355     cm_req_t    req;
5356
5357     RDR_InitReq(&req, FALSE);
5358
5359     osi_Log1(afsd_logp, "RDR_ReleaseFid Count=%u", pReleaseFidCB->Count);
5360
5361     Length = sizeof(AFSReleaseFidResultCB) + (pReleaseFidCB->Count ? pReleaseFidCB->Count-1 : 0) * sizeof(AFSFidResult);
5362     if (Length > ResultBufferLength) {
5363         *ResultCB = (AFSCommResult *)malloc(sizeof(AFSCommResult) );
5364         if (!(*ResultCB))
5365             return;
5366         memset( *ResultCB, 0, sizeof(AFSCommResult));
5367         (*ResultCB)->ResultStatus = STATUS_BUFFER_OVERFLOW;
5368         return;
5369     }
5370     *ResultCB = (AFSCommResult *)malloc( Length + sizeof( AFSCommResult) );
5371     if (!(*ResultCB))
5372         return;
5373     memset( *ResultCB, '\0', Length );
5374     (*ResultCB)->ResultBufferLength = Length;
5375     pResultCB = (AFSReleaseFidResultCB *)(*ResultCB)->ResultData;
5376
5377     for ( index = 0; index < pReleaseFidCB->Count; index++ )
5378     {
5379         cm_scache_t *scp = NULL;
5380         cm_fid_t    Fid;
5381
5382         Fid.cell   = pResultCB->Result[index].FileID.Cell   = pReleaseFidCB->FileID[index].Cell;
5383         Fid.volume = pResultCB->Result[index].FileID.Volume = pReleaseFidCB->FileID[index].Volume;
5384         Fid.vnode  = pResultCB->Result[index].FileID.Vnode  = pReleaseFidCB->FileID[index].Vnode;
5385         Fid.unique = pResultCB->Result[index].FileID.Unique = pReleaseFidCB->FileID[index].Unique;
5386         Fid.hash   = pResultCB->Result[index].FileID.Hash   = pReleaseFidCB->FileID[index].Hash;
5387
5388         osi_Log4( afsd_logp,
5389                   "RDR_ReleaseFid File FID cell=0x%x vol=0x%x vn=0x%x uniq=0x%x",
5390                   Fid.cell, Fid.volume, Fid.vnode, Fid.unique);
5391
5392         scp = cm_FindSCache(&Fid);
5393         if (scp) {
5394             lock_ObtainWrite(&scp->rw);
5395             scp->flags &= ~CM_SCACHEFLAG_RDR_IN_USE;
5396             lock_ReleaseWrite(&scp->rw);
5397
5398             cm_ReleaseSCache(scp);
5399         }
5400         pResultCB->Result[index].Status = 0;
5401     }
5402     pResultCB->Count = pReleaseFidCB->Count;
5403
5404     (*ResultCB)->ResultStatus = 0;
5405     osi_Log0(afsd_logp, "RDR_ReleaseFid SUCCESS");
5406     return;
5407 }
5408
5409 /*
5410  * The redirector makes several assumptions regarding the
5411  * SRVSVC and WKSSVC pipes transactions.  First, the interface
5412  * versions are those indicated below.  Secondly, the encoding
5413  * will be performed using NDR version 2.  These assumptions
5414  * may not hold in the future and end-to-end MSRPC Bind
5415  * negotiations may need to be supported.  Of course, these
5416  * are the only interface versions that are supported by the
5417  * service.
5418  */
5419 #define MSRPC_PIPE_PREFIX L".\\"
5420
5421 static const UUID MSRPC_SRVSVC_UUID = {0x4B324FC8, 0x1670, 0x01D3,
5422                                        {0x12, 0x78, 0x5A, 0x47, 0xBF, 0x6E, 0xE1, 0x88}};
5423 #define MSRPC_SRVSVC_NAME L"PIPE\\SRVSVC"
5424 #define MSRPC_SRVSVC_VERS 3
5425
5426 static const UUID MSRPC_WKSSVC_UUID = {0x6BFFD098, 0xA112, 0x3610,
5427                                        {0x98, 0x33, 0x46, 0xC3, 0xF8, 0x7E, 0x34, 0x5A}};
5428 #define MSRPC_WKSSVC_NAME L"PIPE\\WKSSVC"
5429 #define MSRPC_WKSSVC_VERS 1
5430
5431 static const UUID MSRPC_NDR_UUID = {0x8A885D04, 0x1CEB, 0x11C9,
5432                                     {0x9F, 0xE8, 0x08, 0x00, 0x2B, 0x10, 0x48, 0x60}};
5433 #define MSRPC_NDR_NAME    L"NDR"
5434 #define MSRPC_NDR_VERS    2
5435
5436 extern RPC_IF_HANDLE srvsvc_v3_0_s_ifspec;
5437 extern RPC_IF_HANDLE wkssvc_v1_0_s_ifspec;
5438
5439 void
5440 RDR_PipeOpen( IN cm_user_t *userp,
5441               IN AFSFileID  ParentId,
5442               IN WCHAR     *Name,
5443               IN DWORD      NameLength,
5444               IN AFSPipeOpenCloseRequestCB *pPipe_CB,
5445               IN BOOL bWow64,
5446               IN DWORD ResultBufferLength,
5447               IN OUT AFSCommResult **ResultCB)
5448 {
5449     cm_fid_t    ParentFid;
5450     cm_fid_t    RootFid;
5451
5452     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
5453     if (!(*ResultCB))
5454         return;
5455
5456     memset( *ResultCB,
5457             '\0',
5458             sizeof( AFSCommResult));
5459
5460     /* Get the active directory */
5461     ParentFid.cell = ParentId.Cell;
5462     ParentFid.volume = ParentId.Volume;
5463     ParentFid.vnode = ParentId.Vnode;
5464     ParentFid.unique = ParentId.Unique;
5465     ParentFid.hash = ParentId.Hash;
5466
5467     /* Get the root directory */
5468     RootFid.cell = pPipe_CB->RootId.Cell;
5469     RootFid.volume = pPipe_CB->RootId.Volume;
5470     RootFid.vnode = pPipe_CB->RootId.Vnode;
5471     RootFid.unique = pPipe_CB->RootId.Unique;
5472     RootFid.hash = pPipe_CB->RootId.Hash;
5473
5474     /* Create the pipe index */
5475     (*ResultCB)->ResultStatus =
5476       RDR_SetupPipe( pPipe_CB->RequestId, &ParentFid, &RootFid,
5477                      Name, NameLength, userp);
5478     return;
5479 }
5480
5481
5482 void
5483 RDR_PipeClose( IN cm_user_t *userp,
5484                IN AFSFileID  ParentId,
5485                IN AFSPipeOpenCloseRequestCB *pPipe_CB,
5486                IN BOOL bWow64,
5487                IN DWORD ResultBufferLength,
5488                IN OUT AFSCommResult **ResultCB)
5489 {
5490     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
5491     if (!(*ResultCB))
5492         return;
5493
5494     memset( *ResultCB,
5495             '\0',
5496             sizeof( AFSCommResult));
5497
5498     /* Cleanup the pipe index */
5499     RDR_CleanupPipe(pPipe_CB->RequestId);
5500
5501     return;
5502 }
5503
5504
5505 void
5506 RDR_PipeWrite( IN cm_user_t *userp,
5507                IN AFSFileID  ParentId,
5508                IN AFSPipeIORequestCB *pPipe_CB,
5509                IN BYTE *pPipe_Data,
5510                IN BOOL bWow64,
5511                IN DWORD ResultBufferLength,
5512                IN OUT AFSCommResult **ResultCB)
5513 {
5514     AFSPipeIOResultCB *pResultCB;
5515     cm_scache_t *dscp = NULL;
5516     afs_uint32  code;
5517     cm_req_t    req;
5518     DWORD       status;
5519
5520     RDR_InitReq(&req, bWow64);
5521
5522     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + sizeof(AFSPipeIOResultCB));
5523     if (!(*ResultCB))
5524         return;
5525
5526     memset( *ResultCB,
5527             '\0',
5528             sizeof( AFSCommResult) + sizeof(AFSPipeIOResultCB));
5529
5530     pResultCB = (AFSPipeIOResultCB *)(*ResultCB)->ResultData;
5531
5532     code = RDR_Pipe_Write( pPipe_CB->RequestId, pPipe_CB->BufferLength, pPipe_Data, &req, userp);
5533     if (code) {
5534         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5535         (*ResultCB)->ResultStatus = status;
5536         return;
5537     }
5538
5539     pResultCB->BytesProcessed = pPipe_CB->BufferLength;
5540     (*ResultCB)->ResultBufferLength = sizeof( AFSPipeIOResultCB);
5541 }
5542
5543
5544 void
5545 RDR_PipeRead( IN cm_user_t *userp,
5546               IN AFSFileID  ParentId,
5547               IN AFSPipeIORequestCB *pPipe_CB,
5548               IN BOOL bWow64,
5549               IN DWORD ResultBufferLength,
5550               IN OUT AFSCommResult **ResultCB)
5551 {
5552     BYTE *pPipe_Data;
5553     cm_scache_t *dscp = NULL;
5554     afs_uint32  code;
5555     cm_req_t    req;
5556     DWORD       status;
5557
5558     RDR_InitReq(&req, bWow64);
5559
5560     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + ResultBufferLength);
5561     if (!(*ResultCB))
5562         return;
5563
5564     memset( *ResultCB,
5565             '\0',
5566             sizeof( AFSCommResult));
5567
5568     pPipe_Data = (BYTE *)(*ResultCB)->ResultData;
5569
5570     code = RDR_Pipe_Read( pPipe_CB->RequestId, ResultBufferLength, pPipe_Data,
5571                           &(*ResultCB)->ResultBufferLength, &req, userp);
5572     if (code) {
5573         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5574         (*ResultCB)->ResultStatus = status;
5575         return;
5576     }
5577 }
5578
5579
5580 void
5581 RDR_PipeSetInfo( IN cm_user_t *userp,
5582                  IN AFSFileID  ParentId,
5583                  IN AFSPipeInfoRequestCB *pPipeInfo_CB,
5584                  IN BYTE *pPipe_Data,
5585                  IN BOOL bWow64,
5586                  IN DWORD ResultBufferLength,
5587                  IN OUT AFSCommResult **ResultCB)
5588 {
5589     cm_scache_t *dscp = NULL;
5590     cm_req_t    req;
5591     DWORD       status;
5592
5593     RDR_InitReq(&req, bWow64);
5594
5595     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult));
5596     if (!(*ResultCB))
5597         return;
5598
5599     memset( *ResultCB,
5600             '\0',
5601             sizeof( AFSCommResult));
5602
5603     status = RDR_Pipe_SetInfo( pPipeInfo_CB->RequestId, pPipeInfo_CB->InformationClass,
5604                                pPipeInfo_CB->BufferLength, pPipe_Data, &req, userp);
5605
5606     (*ResultCB)->ResultStatus = status;
5607 }
5608
5609
5610 void
5611 RDR_PipeQueryInfo( IN cm_user_t *userp,
5612                    IN AFSFileID  ParentId,
5613                    IN AFSPipeInfoRequestCB *pPipeInfo_CB,
5614                    IN BOOL bWow64,
5615                    IN DWORD ResultBufferLength,
5616                    IN OUT AFSCommResult **ResultCB)
5617 {
5618     BYTE *pPipe_Data;
5619     cm_scache_t *dscp = NULL;
5620     cm_req_t    req;
5621     DWORD       status;
5622
5623     RDR_InitReq(&req, bWow64);
5624
5625     *ResultCB = (AFSCommResult *)malloc( sizeof( AFSCommResult) + ResultBufferLength);
5626     if (!(*ResultCB))
5627         return;
5628
5629     memset( *ResultCB,
5630             '\0',
5631             sizeof( AFSCommResult) + sizeof(AFSPipeIOResultCB));
5632
5633     pPipe_Data = (BYTE *)(*ResultCB)->ResultData;
5634
5635     status = RDR_Pipe_QueryInfo( pPipeInfo_CB->RequestId, pPipeInfo_CB->InformationClass,
5636                                  ResultBufferLength, pPipe_Data,
5637                                  &(*ResultCB)->ResultBufferLength, &req, userp);
5638
5639     (*ResultCB)->ResultStatus = status;
5640 }
5641
5642 void
5643 RDR_PipeTransceive( IN cm_user_t     *userp,
5644                     IN AFSFileID  ParentId,
5645                     IN AFSPipeIORequestCB *pPipe_CB,
5646                     IN BYTE *pPipe_InData,
5647                     IN BOOL bWow64,
5648                     IN DWORD ResultBufferLength,
5649                     IN OUT AFSCommResult **ResultCB)
5650 {
5651     /*
5652      * This function processes a Pipe Service request
5653      * that would normally be sent to a LAN Manager server
5654      * across an authenticated SMB-PIPE/MSRPC/SVC request
5655      * stack.  The request is being sent here because the
5656      * application (e.g., Explorer Shell or Common Control File
5657      * dialog) believes that because the UNC path it is
5658      * processing has specified a server name that is not
5659      * "." and that the Server is remote and that the Share
5660      * list cannot be obtained using the Network Provider
5661      * interface.
5662      *
5663      * The file system driver is faking the Bind-Ack response
5664      * to the MSRPC Bind request but cannot decode the NDR
5665      * encoded Pipe Service requests.  For that we will use
5666      * the service's MSRPC module.  However, unlike the SMB
5667      * server usage we must fake the MSRPC Bind exchange and
5668      * map the PipeName to an interface instead of using the
5669      * GUID specified in the MSRPC Bind request.
5670      *
5671      * None of the requests that are being processed by the
5672      * service require authentication.  As a result the userp
5673      * parameter will be ignored.
5674      *
5675      * Although there are dozens of Pipe Services, the only
5676      * ones that we are implementing are WKSSVC and SRVSVC.
5677      * These support NetShareEnum, NetShareGetInfo,
5678      * NetServerGetInfo, and NetWorkstaGetInfo which are
5679      * commonly queried by NET VIEW, the Explorer Shell,
5680      * and the Common Control File dialog.
5681      */
5682     BYTE *pPipe_OutData;
5683     cm_scache_t *dscp = NULL;
5684     afs_uint32  code;
5685     cm_req_t    req;
5686     DWORD       status;
5687     DWORD Length = ResultBufferLength + sizeof( AFSCommResult);
5688
5689     RDR_InitReq(&req, bWow64);
5690
5691     *ResultCB = (AFSCommResult *)malloc( Length);
5692     if (!(*ResultCB))
5693         return;
5694     memset( *ResultCB, '\0', Length );
5695
5696     code = RDR_Pipe_Write( pPipe_CB->RequestId, pPipe_CB->BufferLength, pPipe_InData, &req, userp);
5697     if (code) {
5698         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5699         osi_Log2( afsd_logp, "RDR_Pipe_Transceive Write FAILURE code=0x%x status=0x%x",
5700                   code, status);
5701         (*ResultCB)->ResultStatus = status;
5702         return;
5703     }
5704
5705     pPipe_OutData = (BYTE *)(*ResultCB)->ResultData;
5706     code = RDR_Pipe_Read( pPipe_CB->RequestId, ResultBufferLength, pPipe_OutData,
5707                           &(*ResultCB)->ResultBufferLength, &req, userp);
5708     if (code) {
5709         smb_MapNTError(cm_MapRPCError(code, &req), &status, TRUE);
5710         osi_Log2( afsd_logp, "RDR_Pipe_Transceive Read FAILURE code=0x%x status=0x%x",
5711                   code, status);
5712         (*ResultCB)->ResultStatus = status;
5713         return;
5714     }
5715
5716     (*ResultCB)->ResultStatus = 0;
5717     osi_Log0(afsd_logp, "RDR_Pipe_Transceive SUCCESS");
5718 }