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