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