[NTOSKRNL] Use faster internal helper to query name
[reactos.git] / ntoskrnl / io / iomgr / file.c
1 /*
2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/iomgr/file.c
5 * PURPOSE: Functions that deal with managing the FILE_OBJECT itself.
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Gunnar Dalsnes
8 * Eric Kohl
9 * Filip Navara (navaraf@reactos.org)
10 * Pierre Schweitzer
11 */
12
13 /* INCLUDES *****************************************************************/
14
15 #include <ntoskrnl.h>
16 #define NDEBUG
17 #include <debug.h>
18
19 extern ERESOURCE IopSecurityResource;
20
21 /* PRIVATE FUNCTIONS *********************************************************/
22
23 VOID
24 NTAPI
25 IopCheckBackupRestorePrivilege(IN PACCESS_STATE AccessState,
26 IN OUT PULONG CreateOptions,
27 IN KPROCESSOR_MODE PreviousMode,
28 IN ULONG Disposition)
29 {
30 ACCESS_MASK DesiredAccess, ReadAccess, WriteAccess;
31 PRIVILEGE_SET Privileges;
32 BOOLEAN AccessGranted, HaveBackupPriv = FALSE, CheckRestore = FALSE;
33 PAGED_CODE();
34
35 /* Don't do anything if privileges were checked already */
36 if (AccessState->Flags & SE_BACKUP_PRIVILEGES_CHECKED) return;
37
38 /* Check if the file was actually opened for backup purposes */
39 if (*CreateOptions & FILE_OPEN_FOR_BACKUP_INTENT)
40 {
41 /* Set the check flag since were doing it now */
42 AccessState->Flags |= SE_BACKUP_PRIVILEGES_CHECKED;
43
44 /* Set the access masks required */
45 ReadAccess = READ_CONTROL |
46 ACCESS_SYSTEM_SECURITY |
47 FILE_GENERIC_READ |
48 FILE_TRAVERSE;
49 WriteAccess = WRITE_DAC |
50 WRITE_OWNER |
51 ACCESS_SYSTEM_SECURITY |
52 FILE_GENERIC_WRITE |
53 FILE_ADD_FILE |
54 FILE_ADD_SUBDIRECTORY |
55 DELETE;
56 DesiredAccess = AccessState->RemainingDesiredAccess;
57
58 /* Check if desired access was the maximum */
59 if (DesiredAccess & MAXIMUM_ALLOWED)
60 {
61 /* Then add all the access masks required */
62 DesiredAccess |= (ReadAccess | WriteAccess);
63 }
64
65 /* Check if the file already exists */
66 if (Disposition & FILE_OPEN)
67 {
68 /* Check if desired access has the read mask */
69 if (ReadAccess & DesiredAccess)
70 {
71 /* Setup the privilege check lookup */
72 Privileges.PrivilegeCount = 1;
73 Privileges.Control = PRIVILEGE_SET_ALL_NECESSARY;
74 Privileges.Privilege[0].Luid = SeBackupPrivilege;
75 Privileges.Privilege[0].Attributes = 0;
76 AccessGranted = SePrivilegeCheck(&Privileges,
77 &AccessState->
78 SubjectSecurityContext,
79 PreviousMode);
80 if (AccessGranted)
81 {
82 /* Remember that backup was allowed */
83 HaveBackupPriv = TRUE;
84
85 /* Append the privileges and update the access state */
86 SeAppendPrivileges(AccessState, &Privileges);
87 AccessState->PreviouslyGrantedAccess |= (DesiredAccess & ReadAccess);
88 AccessState->RemainingDesiredAccess &= ~ReadAccess;
89 DesiredAccess &= ~ReadAccess;
90
91 /* Set backup privilege for the token */
92 AccessState->Flags |= TOKEN_HAS_BACKUP_PRIVILEGE;
93 }
94 }
95 }
96 else
97 {
98 /* Caller is creating the file, check restore privileges later */
99 CheckRestore = TRUE;
100 }
101
102 /* Check if caller wants write access or if it's creating a file */
103 if ((WriteAccess & DesiredAccess) || (CheckRestore))
104 {
105 /* Setup the privilege lookup and do it */
106 Privileges.PrivilegeCount = 1;
107 Privileges.Control = PRIVILEGE_SET_ALL_NECESSARY;
108 Privileges.Privilege[0].Luid = SeRestorePrivilege;
109 Privileges.Privilege[0].Attributes = 0;
110 AccessGranted = SePrivilegeCheck(&Privileges,
111 &AccessState->SubjectSecurityContext,
112 PreviousMode);
113 if (AccessGranted)
114 {
115 /* Remember that privilege was given */
116 HaveBackupPriv = TRUE;
117
118 /* Append the privileges and update the access state */
119 SeAppendPrivileges(AccessState, &Privileges);
120 AccessState->PreviouslyGrantedAccess |= (DesiredAccess & WriteAccess);
121 AccessState->RemainingDesiredAccess &= ~WriteAccess;
122
123 /* Set restore privilege for the token */
124 AccessState->Flags |= TOKEN_HAS_RESTORE_PRIVILEGE;
125 }
126 }
127
128 /* If we don't have the privilege, remove the option */
129 if (!HaveBackupPriv) *CreateOptions &= ~FILE_OPEN_FOR_BACKUP_INTENT;
130 }
131 }
132
133 NTSTATUS
134 NTAPI
135 IopCheckDeviceAndDriver(IN POPEN_PACKET OpenPacket,
136 IN PDEVICE_OBJECT DeviceObject)
137 {
138 /* Make sure the object is valid */
139 if ((IoGetDevObjExtension(DeviceObject)->ExtensionFlags &
140 (DOE_UNLOAD_PENDING |
141 DOE_DELETE_PENDING |
142 DOE_REMOVE_PENDING |
143 DOE_REMOVE_PROCESSED)) ||
144 (DeviceObject->Flags & DO_DEVICE_INITIALIZING))
145 {
146 /* It's unloading or initializing, so fail */
147 DPRINT1("You are seeing this because the following ROS driver: %wZ\n"
148 " sucks. Please fix it's AddDevice Routine\n",
149 &DeviceObject->DriverObject->DriverName);
150 return STATUS_NO_SUCH_DEVICE;
151 }
152 else if ((DeviceObject->Flags & DO_EXCLUSIVE) &&
153 (DeviceObject->ReferenceCount) &&
154 !(OpenPacket->RelatedFileObject) &&
155 !(OpenPacket->Options & IO_ATTACH_DEVICE))
156 {
157 return STATUS_ACCESS_DENIED;
158 }
159
160 else
161 {
162 /* Increase reference count */
163 InterlockedIncrement(&DeviceObject->ReferenceCount);
164 return STATUS_SUCCESS;
165 }
166 }
167
168 VOID
169 NTAPI
170 IopDoNameTransmogrify(IN PIRP Irp,
171 IN PFILE_OBJECT FileObject,
172 IN PREPARSE_DATA_BUFFER DataBuffer)
173 {
174 PWSTR Buffer;
175 USHORT Length;
176 USHORT RequiredLength;
177 PWSTR NewBuffer;
178
179 PAGED_CODE();
180
181 ASSERT(Irp->IoStatus.Status == STATUS_REPARSE);
182 ASSERT(Irp->IoStatus.Information == IO_REPARSE_TAG_MOUNT_POINT);
183 ASSERT(Irp->Tail.Overlay.AuxiliaryBuffer != NULL);
184 ASSERT(DataBuffer != NULL);
185 ASSERT(DataBuffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT);
186 ASSERT(DataBuffer->ReparseDataLength < MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
187 ASSERT(DataBuffer->Reserved < MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
188
189 /* First of all, validate data */
190 if (DataBuffer->ReparseDataLength < REPARSE_DATA_BUFFER_HEADER_SIZE ||
191 (DataBuffer->SymbolicLinkReparseBuffer.PrintNameLength +
192 DataBuffer->SymbolicLinkReparseBuffer.SubstituteNameLength +
193 FIELD_OFFSET(REPARSE_DATA_BUFFER, MountPointReparseBuffer.PathBuffer[0])) > MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
194 {
195 Irp->IoStatus.Status = STATUS_IO_REPARSE_DATA_INVALID;
196 }
197
198 /* Everything went right */
199 if (NT_SUCCESS(Irp->IoStatus.Status))
200 {
201 /* Compute buffer & length */
202 Buffer = (PWSTR)((ULONG_PTR)DataBuffer->MountPointReparseBuffer.PathBuffer +
203 DataBuffer->MountPointReparseBuffer.SubstituteNameOffset);
204 Length = DataBuffer->MountPointReparseBuffer.SubstituteNameLength;
205
206 /* Check we don't overflow */
207 if (((ULONG)MAXUSHORT - DataBuffer->Reserved) <= (Length + sizeof(UNICODE_NULL)))
208 {
209 Irp->IoStatus.Status = STATUS_IO_REPARSE_DATA_INVALID;
210 }
211 else
212 {
213 /* Compute how much mem we'll need */
214 RequiredLength = DataBuffer->Reserved + Length + sizeof(UNICODE_NULL);
215
216 /* Check if FileObject can already hold what we need */
217 if (FileObject->FileName.MaximumLength >= RequiredLength)
218 {
219 NewBuffer = FileObject->FileName.Buffer;
220 }
221 else
222 {
223 /* Allocate otherwise */
224 NewBuffer = ExAllocatePoolWithTag(PagedPool, RequiredLength, TAG_IO_NAME);
225 if (NewBuffer == NULL)
226 {
227 Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
228 }
229 }
230 }
231 }
232
233 /* Everything went right */
234 if (NT_SUCCESS(Irp->IoStatus.Status))
235 {
236 /* Copy reserved */
237 if (DataBuffer->Reserved)
238 {
239 RtlMoveMemory((PWSTR)((ULONG_PTR)NewBuffer + Length),
240 (PWSTR)((ULONG_PTR)FileObject->FileName.Buffer + FileObject->FileName.Length - DataBuffer->Reserved),
241 DataBuffer->Reserved);
242 }
243
244 /* Then, buffer */
245 if (Length)
246 {
247 RtlCopyMemory(NewBuffer, Buffer, Length);
248 }
249
250 /* And finally replace buffer if new one was allocated */
251 FileObject->FileName.Length = RequiredLength - sizeof(UNICODE_NULL);
252 if (NewBuffer != FileObject->FileName.Buffer)
253 {
254 if (FileObject->FileName.Buffer)
255 {
256 ExFreePoolWithTag(FileObject->FileName.Buffer, TAG_IO_NAME);
257 }
258
259 FileObject->FileName.Buffer = NewBuffer;
260 FileObject->FileName.MaximumLength = RequiredLength;
261 FileObject->FileName.Buffer[RequiredLength / sizeof(WCHAR) - 1] = UNICODE_NULL;
262 }
263 }
264
265 /* We don't need them anymore - it was allocated by the driver */
266 ExFreePool(DataBuffer);
267 }
268
269 NTSTATUS
270 NTAPI
271 IopParseDevice(IN PVOID ParseObject,
272 IN PVOID ObjectType,
273 IN OUT PACCESS_STATE AccessState,
274 IN KPROCESSOR_MODE AccessMode,
275 IN ULONG Attributes,
276 IN OUT PUNICODE_STRING CompleteName,
277 IN OUT PUNICODE_STRING RemainingName,
278 IN OUT PVOID Context,
279 IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL,
280 OUT PVOID *Object)
281 {
282 POPEN_PACKET OpenPacket = (POPEN_PACKET)Context;
283 PDEVICE_OBJECT OriginalDeviceObject = (PDEVICE_OBJECT)ParseObject;
284 PDEVICE_OBJECT DeviceObject, OwnerDevice;
285 NTSTATUS Status;
286 PFILE_OBJECT FileObject;
287 PVPB Vpb = NULL;
288 PIRP Irp;
289 PIO_STACK_LOCATION StackLoc;
290 IO_SECURITY_CONTEXT SecurityContext;
291 IO_STATUS_BLOCK IoStatusBlock;
292 BOOLEAN DirectOpen = FALSE, OpenCancelled, UseDummyFile;
293 OBJECT_ATTRIBUTES ObjectAttributes;
294 KIRQL OldIrql;
295 PDUMMY_FILE_OBJECT LocalFileObject;
296 PFILE_BASIC_INFORMATION FileBasicInfo;
297 ULONG ReturnLength;
298 KPROCESSOR_MODE CheckMode;
299 BOOLEAN VolumeOpen = FALSE;
300 ACCESS_MASK DesiredAccess, GrantedAccess;
301 BOOLEAN AccessGranted, LockHeld = FALSE;
302 PPRIVILEGE_SET Privileges = NULL;
303 UNICODE_STRING FileString;
304 USHORT Attempt;
305 IOTRACE(IO_FILE_DEBUG, "ParseObject: %p. RemainingName: %wZ\n",
306 ParseObject, RemainingName);
307
308 for (Attempt = 0; Attempt < IOP_MAX_REPARSE_TRAVERSAL; ++Attempt)
309 {
310 /* Assume failure */
311 *Object = NULL;
312
313 /* Validate the open packet */
314 if (!IopValidateOpenPacket(OpenPacket)) return STATUS_OBJECT_TYPE_MISMATCH;
315
316 /* Valide reparse point in case we traversed a mountpoint */
317 if (OpenPacket->TraversedMountPoint)
318 {
319 /* This is a reparse point we understand */
320 ASSERT(OpenPacket->Information == IO_REPARSE_TAG_MOUNT_POINT);
321
322 /* Make sure we're dealing with correct DO */
323 if (OriginalDeviceObject->DeviceType != FILE_DEVICE_DISK &&
324 OriginalDeviceObject->DeviceType != FILE_DEVICE_CD_ROM &&
325 OriginalDeviceObject->DeviceType != FILE_DEVICE_VIRTUAL_DISK &&
326 OriginalDeviceObject->DeviceType != FILE_DEVICE_TAPE)
327 {
328 OpenPacket->FinalStatus = STATUS_IO_REPARSE_DATA_INVALID;
329 return STATUS_IO_REPARSE_DATA_INVALID;
330 }
331 }
332
333 /* Check if we have a related file object */
334 if (OpenPacket->RelatedFileObject)
335 {
336 /* Use the related file object's device object */
337 OriginalDeviceObject = OpenPacket->RelatedFileObject->DeviceObject;
338 }
339
340 /* Validate device status */
341 Status = IopCheckDeviceAndDriver(OpenPacket, OriginalDeviceObject);
342 if (!NT_SUCCESS(Status))
343 {
344 /* We failed, return status */
345 OpenPacket->FinalStatus = Status;
346 return Status;
347 }
348
349 /* Map the generic mask and set the new mapping in the access state */
350 RtlMapGenericMask(&AccessState->RemainingDesiredAccess,
351 &IoFileObjectType->TypeInfo.GenericMapping);
352 RtlMapGenericMask(&AccessState->OriginalDesiredAccess,
353 &IoFileObjectType->TypeInfo.GenericMapping);
354 SeSetAccessStateGenericMapping(AccessState,
355 &IoFileObjectType->TypeInfo.GenericMapping);
356 DesiredAccess = AccessState->RemainingDesiredAccess;
357
358 /* Check what kind of access checks to do */
359 if ((AccessMode != KernelMode) ||
360 (OpenPacket->Options & IO_FORCE_ACCESS_CHECK))
361 {
362 /* Call is from user-mode or kernel is forcing checks */
363 CheckMode = UserMode;
364 }
365 else
366 {
367 /* Call is from the kernel */
368 CheckMode = KernelMode;
369 }
370
371 /* Check privilege for backup or restore operation */
372 IopCheckBackupRestorePrivilege(AccessState,
373 &OpenPacket->CreateOptions,
374 CheckMode,
375 OpenPacket->Disposition);
376
377 /* Check if we are re-parsing */
378 if (((OpenPacket->Override) && !(RemainingName->Length)) ||
379 (AccessState->Flags & SE_BACKUP_PRIVILEGES_CHECKED))
380 {
381 /* Get granted access from the last call */
382 DesiredAccess |= AccessState->PreviouslyGrantedAccess;
383 }
384
385 /* Check if this is a volume open */
386 if ((OpenPacket->RelatedFileObject) &&
387 (OpenPacket->RelatedFileObject->Flags & FO_VOLUME_OPEN) &&
388 !(RemainingName->Length))
389 {
390 /* It is */
391 VolumeOpen = TRUE;
392 }
393
394 /* Now check if we need access checks */
395 if (((AccessMode != KernelMode) ||
396 (OpenPacket->Options & IO_FORCE_ACCESS_CHECK)) &&
397 (!(OpenPacket->RelatedFileObject) || (VolumeOpen)) &&
398 !(OpenPacket->Override))
399 {
400 KeEnterCriticalRegion();
401 ExAcquireResourceSharedLite(&IopSecurityResource, TRUE);
402
403 /* Check if a device object is being parsed */
404 if (!RemainingName->Length)
405 {
406 /* Lock the subject context */
407 SeLockSubjectContext(&AccessState->SubjectSecurityContext);
408 LockHeld = TRUE;
409
410 /* Do access check */
411 AccessGranted = SeAccessCheck(OriginalDeviceObject->
412 SecurityDescriptor,
413 &AccessState->SubjectSecurityContext,
414 LockHeld,
415 DesiredAccess,
416 0,
417 &Privileges,
418 &IoFileObjectType->
419 TypeInfo.GenericMapping,
420 UserMode,
421 &GrantedAccess,
422 &Status);
423 if (Privileges)
424 {
425 /* Append and free the privileges */
426 SeAppendPrivileges(AccessState, Privileges);
427 SeFreePrivileges(Privileges);
428 }
429
430 /* Check if we got access */
431 if (AccessGranted)
432 {
433 /* Update access state */
434 AccessState->PreviouslyGrantedAccess |= GrantedAccess;
435 AccessState->RemainingDesiredAccess &= ~(GrantedAccess |
436 MAXIMUM_ALLOWED);
437 OpenPacket->Override= TRUE;
438 }
439
440 FileString.Length = 8;
441 FileString.MaximumLength = 8;
442 FileString.Buffer = L"File";
443
444 /* Do Audit/Alarm for open operation */
445 SeOpenObjectAuditAlarm(&FileString,
446 OriginalDeviceObject,
447 CompleteName,
448 OriginalDeviceObject->SecurityDescriptor,
449 AccessState,
450 FALSE,
451 AccessGranted,
452 UserMode,
453 &AccessState->GenerateOnClose);
454 }
455 else
456 {
457 /* Check if we need to do traverse validation */
458 if (!(AccessState->Flags & TOKEN_HAS_TRAVERSE_PRIVILEGE) ||
459 ((OriginalDeviceObject->DeviceType == FILE_DEVICE_DISK) ||
460 (OriginalDeviceObject->DeviceType == FILE_DEVICE_CD_ROM)))
461 {
462 /* Check if this is a restricted token */
463 if (!(AccessState->Flags & TOKEN_IS_RESTRICTED))
464 {
465 /* Do the FAST traverse check */
466 AccessGranted = SeFastTraverseCheck(OriginalDeviceObject->SecurityDescriptor,
467 AccessState,
468 FILE_TRAVERSE,
469 UserMode);
470 }
471 else
472 {
473 /* Fail */
474 AccessGranted = FALSE;
475 }
476
477 /* Check if we failed to get access */
478 if (!AccessGranted)
479 {
480 /* Lock the subject context */
481 SeLockSubjectContext(&AccessState->SubjectSecurityContext);
482 LockHeld = TRUE;
483
484 /* Do access check */
485 AccessGranted = SeAccessCheck(OriginalDeviceObject->
486 SecurityDescriptor,
487 &AccessState->SubjectSecurityContext,
488 LockHeld,
489 FILE_TRAVERSE,
490 0,
491 &Privileges,
492 &IoFileObjectType->
493 TypeInfo.GenericMapping,
494 UserMode,
495 &GrantedAccess,
496 &Status);
497 if (Privileges)
498 {
499 /* Append and free the privileges */
500 SeAppendPrivileges(AccessState, Privileges);
501 SeFreePrivileges(Privileges);
502 }
503 }
504
505 /* FIXME: Do Audit/Alarm for traverse check */
506 }
507 else
508 {
509 /* Access automatically granted */
510 AccessGranted = TRUE;
511 }
512 }
513
514 ExReleaseResourceLite(&IopSecurityResource);
515 KeLeaveCriticalRegion();
516
517 /* Check if we hold the lock */
518 if (LockHeld)
519 {
520 /* Release it */
521 SeUnlockSubjectContext(&AccessState->SubjectSecurityContext);
522 }
523
524 /* Check if access failed */
525 if (!AccessGranted)
526 {
527 /* Dereference the device and fail */
528 DPRINT1("Traverse access failed!\n");
529 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
530 return STATUS_ACCESS_DENIED;
531 }
532 }
533
534 /* Check if we can simply use a dummy file */
535 UseDummyFile = ((OpenPacket->QueryOnly) || (OpenPacket->DeleteOnly));
536
537 #if 1
538 /* FIXME: Small hack still exists, have to check why...
539 * This is triggered multiple times by usetup and then once per boot.
540 */
541 if (ExpInTextModeSetup &&
542 !(DirectOpen) &&
543 !(RemainingName->Length) &&
544 !(OpenPacket->RelatedFileObject) &&
545 ((wcsstr(CompleteName->Buffer, L"Harddisk")) ||
546 (wcsstr(CompleteName->Buffer, L"Floppy"))) &&
547 !(UseDummyFile))
548 {
549 DPRINT1("Using IopParseDevice() hack. Requested invalid attributes: %lx\n",
550 DesiredAccess & ~(SYNCHRONIZE |
551 FILE_READ_ATTRIBUTES |
552 READ_CONTROL |
553 ACCESS_SYSTEM_SECURITY |
554 WRITE_OWNER |
555 WRITE_DAC));
556 DirectOpen = TRUE;
557 }
558 #endif
559
560 /* Check if this is a direct open */
561 if (!(RemainingName->Length) &&
562 !(OpenPacket->RelatedFileObject) &&
563 ((DesiredAccess & ~(SYNCHRONIZE |
564 FILE_READ_ATTRIBUTES |
565 READ_CONTROL |
566 ACCESS_SYSTEM_SECURITY |
567 WRITE_OWNER |
568 WRITE_DAC)) == 0) &&
569 !(UseDummyFile))
570 {
571 /* Remember this for later */
572 DirectOpen = TRUE;
573 }
574
575 /* Check if we have a related FO that wasn't a direct open */
576 if ((OpenPacket->RelatedFileObject) &&
577 !(OpenPacket->RelatedFileObject->Flags & FO_DIRECT_DEVICE_OPEN))
578 {
579 /* The device object is the one we were given */
580 DeviceObject = ParseObject;
581
582 /* Check if the related FO had a VPB */
583 if (OpenPacket->RelatedFileObject->Vpb)
584 {
585 /* Yes, remember it */
586 Vpb = OpenPacket->RelatedFileObject->Vpb;
587
588 /* Reference it */
589 InterlockedIncrement((PLONG)&Vpb->ReferenceCount);
590
591 /* Check if we were given a specific top level device to use */
592 if (OpenPacket->InternalFlags & IOP_USE_TOP_LEVEL_DEVICE_HINT)
593 {
594 DeviceObject = Vpb->DeviceObject;
595 }
596 }
597 }
598 else
599 {
600 /* Check if it has a VPB */
601 if ((OriginalDeviceObject->Vpb) && !(DirectOpen))
602 {
603 /* Check if the VPB is mounted, and mount it */
604 Vpb = IopCheckVpbMounted(OpenPacket,
605 OriginalDeviceObject,
606 RemainingName,
607 &Status);
608 if (!Vpb) return Status;
609
610 /* Get the VPB's device object */
611 DeviceObject = Vpb->DeviceObject;
612 }
613 else
614 {
615 /* The device object is the one we were given */
616 DeviceObject = OriginalDeviceObject;
617 }
618
619 /* If we weren't given a specific top level device, look for an attached device */
620 if (!(OpenPacket->InternalFlags & IOP_USE_TOP_LEVEL_DEVICE_HINT) &&
621 DeviceObject->AttachedDevice)
622 {
623 /* Get the attached device */
624 DeviceObject = IoGetAttachedDevice(DeviceObject);
625 }
626 }
627
628 if (OpenPacket->InternalFlags & IOP_USE_TOP_LEVEL_DEVICE_HINT)
629 {
630 // FIXME: Verify our device object is good to use
631 ASSERT(DirectOpen == FALSE);
632 }
633
634 /* If we traversed a mount point, reset the information */
635 if (OpenPacket->TraversedMountPoint)
636 {
637 OpenPacket->TraversedMountPoint = FALSE;
638 }
639
640 /* Check if this is a secure FSD */
641 if ((DeviceObject->Characteristics & FILE_DEVICE_SECURE_OPEN) &&
642 ((OpenPacket->RelatedFileObject) || (RemainingName->Length)) &&
643 (!VolumeOpen))
644 {
645 Privileges = NULL;
646 GrantedAccess = 0;
647
648 KeEnterCriticalRegion();
649 ExAcquireResourceSharedLite(&IopSecurityResource, TRUE);
650
651 /* Lock the subject context */
652 SeLockSubjectContext(&AccessState->SubjectSecurityContext);
653
654 /* Do access check */
655 AccessGranted = SeAccessCheck(OriginalDeviceObject->SecurityDescriptor,
656 &AccessState->SubjectSecurityContext,
657 TRUE,
658 DesiredAccess,
659 0,
660 &Privileges,
661 &IoFileObjectType->TypeInfo.GenericMapping,
662 UserMode,
663 &GrantedAccess,
664 &Status);
665 if (Privileges != NULL)
666 {
667 /* Append and free the privileges */
668 SeAppendPrivileges(AccessState, Privileges);
669 SeFreePrivileges(Privileges);
670 }
671
672 /* Check if we got access */
673 if (GrantedAccess)
674 {
675 AccessState->PreviouslyGrantedAccess |= GrantedAccess;
676 AccessState->RemainingDesiredAccess &= ~(GrantedAccess | MAXIMUM_ALLOWED);
677 }
678
679 FileString.Length = 8;
680 FileString.MaximumLength = 8;
681 FileString.Buffer = L"File";
682
683 /* Do Audit/Alarm for open operation
684 * NOTA: we audit target device object
685 */
686 SeOpenObjectAuditAlarm(&FileString,
687 DeviceObject,
688 CompleteName,
689 OriginalDeviceObject->SecurityDescriptor,
690 AccessState,
691 FALSE,
692 AccessGranted,
693 UserMode,
694 &AccessState->GenerateOnClose);
695
696 SeUnlockSubjectContext(&AccessState->SubjectSecurityContext);
697
698 ExReleaseResourceLite(&IopSecurityResource);
699 KeLeaveCriticalRegion();
700
701 /* Check if access failed */
702 if (!AccessGranted)
703 {
704 /* Dereference the device and fail */
705 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
706 if (Vpb) IopDereferenceVpbAndFree(Vpb);
707 return STATUS_ACCESS_DENIED;
708 }
709 }
710
711 /* Allocate the IRP */
712 Irp = IoAllocateIrp(DeviceObject->StackSize, TRUE);
713 if (!Irp)
714 {
715 /* Dereference the device and VPB, then fail */
716 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
717 if (Vpb) IopDereferenceVpbAndFree(Vpb);
718 return STATUS_INSUFFICIENT_RESOURCES;
719 }
720
721 /* Now set the IRP data */
722 Irp->RequestorMode = AccessMode;
723 Irp->Flags = IRP_CREATE_OPERATION | IRP_SYNCHRONOUS_API | IRP_DEFER_IO_COMPLETION;
724 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
725 Irp->UserIosb = &IoStatusBlock;
726 Irp->MdlAddress = NULL;
727 Irp->PendingReturned = FALSE;
728 Irp->UserEvent = NULL;
729 Irp->Cancel = FALSE;
730 Irp->CancelRoutine = NULL;
731 Irp->Tail.Overlay.AuxiliaryBuffer = NULL;
732
733 /* Setup the security context */
734 SecurityContext.SecurityQos = SecurityQos;
735 SecurityContext.AccessState = AccessState;
736 SecurityContext.DesiredAccess = AccessState->RemainingDesiredAccess;
737 SecurityContext.FullCreateOptions = OpenPacket->CreateOptions;
738
739 /* Get the I/O Stack location */
740 StackLoc = IoGetNextIrpStackLocation(Irp);
741 StackLoc->Control = 0;
742
743 /* Check what kind of file this is */
744 switch (OpenPacket->CreateFileType)
745 {
746 /* Normal file */
747 case CreateFileTypeNone:
748
749 /* Set the major function and EA Length */
750 StackLoc->MajorFunction = IRP_MJ_CREATE;
751 StackLoc->Parameters.Create.EaLength = OpenPacket->EaLength;
752
753 /* Set the flags */
754 StackLoc->Flags = (UCHAR)OpenPacket->Options;
755 StackLoc->Flags |= !(Attributes & OBJ_CASE_INSENSITIVE) ? SL_CASE_SENSITIVE: 0;
756 break;
757
758 /* Named pipe */
759 case CreateFileTypeNamedPipe:
760
761 /* Set the named pipe MJ and set the parameters */
762 StackLoc->MajorFunction = IRP_MJ_CREATE_NAMED_PIPE;
763 StackLoc->Parameters.CreatePipe.Parameters = OpenPacket->ExtraCreateParameters;
764 break;
765
766 /* Mailslot */
767 case CreateFileTypeMailslot:
768
769 /* Set the mailslot MJ and set the parameters */
770 StackLoc->MajorFunction = IRP_MJ_CREATE_MAILSLOT;
771 StackLoc->Parameters.CreateMailslot.Parameters = OpenPacket->ExtraCreateParameters;
772 break;
773 }
774
775 /* Set the common data */
776 Irp->Overlay.AllocationSize = OpenPacket->AllocationSize;
777 Irp->AssociatedIrp.SystemBuffer = OpenPacket->EaBuffer;
778 StackLoc->Parameters.Create.Options = (OpenPacket->Disposition << 24) |
779 (OpenPacket->CreateOptions &
780 0xFFFFFF);
781 StackLoc->Parameters.Create.FileAttributes = OpenPacket->FileAttributes;
782 StackLoc->Parameters.Create.ShareAccess = OpenPacket->ShareAccess;
783 StackLoc->Parameters.Create.SecurityContext = &SecurityContext;
784
785 /* Check if we really need to create an object */
786 if (!UseDummyFile)
787 {
788 ULONG ObjectSize = sizeof(FILE_OBJECT);
789
790 /* Tag on space for a file object extension */
791 if (OpenPacket->InternalFlags & IOP_CREATE_FILE_OBJECT_EXTENSION)
792 ObjectSize += sizeof(FILE_OBJECT_EXTENSION);
793
794 /* Create the actual file object */
795 InitializeObjectAttributes(&ObjectAttributes,
796 NULL,
797 Attributes,
798 NULL,
799 NULL);
800 Status = ObCreateObject(KernelMode,
801 IoFileObjectType,
802 &ObjectAttributes,
803 AccessMode,
804 NULL,
805 ObjectSize,
806 0,
807 0,
808 (PVOID*)&FileObject);
809 if (!NT_SUCCESS(Status))
810 {
811 /* Create failed, free the IRP */
812 IoFreeIrp(Irp);
813
814 /* Dereference the device and VPB */
815 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
816 if (Vpb) IopDereferenceVpbAndFree(Vpb);
817
818 /* We failed, return status */
819 OpenPacket->FinalStatus = Status;
820 return Status;
821 }
822
823 /* Clear the file object */
824 RtlZeroMemory(FileObject, sizeof(FILE_OBJECT));
825
826 /* Check if this is Synch I/O */
827 if (OpenPacket->CreateOptions &
828 (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
829 {
830 /* Set the synch flag */
831 FileObject->Flags |= FO_SYNCHRONOUS_IO;
832
833 /* Check if it's also alertable */
834 if (OpenPacket->CreateOptions & FILE_SYNCHRONOUS_IO_ALERT)
835 {
836 /* It is, set the alertable flag */
837 FileObject->Flags |= FO_ALERTABLE_IO;
838 }
839 }
840
841 /* Check if this is synch I/O */
842 if (FileObject->Flags & FO_SYNCHRONOUS_IO)
843 {
844 /* Initialize the event */
845 KeInitializeEvent(&FileObject->Lock, SynchronizationEvent, FALSE);
846 }
847
848 /* Check if the caller requested no intermediate buffering */
849 if (OpenPacket->CreateOptions & FILE_NO_INTERMEDIATE_BUFFERING)
850 {
851 /* Set the correct flag for the FSD to read */
852 FileObject->Flags |= FO_NO_INTERMEDIATE_BUFFERING;
853 }
854
855 /* Check if the caller requested write through support */
856 if (OpenPacket->CreateOptions & FILE_WRITE_THROUGH)
857 {
858 /* Set the correct flag for the FSD to read */
859 FileObject->Flags |= FO_WRITE_THROUGH;
860 }
861
862 /* Check if the caller says the file will be only read sequentially */
863 if (OpenPacket->CreateOptions & FILE_SEQUENTIAL_ONLY)
864 {
865 /* Set the correct flag for the FSD to read */
866 FileObject->Flags |= FO_SEQUENTIAL_ONLY;
867 }
868
869 /* Check if the caller believes the file will be only read randomly */
870 if (OpenPacket->CreateOptions & FILE_RANDOM_ACCESS)
871 {
872 /* Set the correct flag for the FSD to read */
873 FileObject->Flags |= FO_RANDOM_ACCESS;
874 }
875
876 /* Check if we were asked to setup a file object extension */
877 if (OpenPacket->InternalFlags & IOP_CREATE_FILE_OBJECT_EXTENSION)
878 {
879 PFILE_OBJECT_EXTENSION FileObjectExtension;
880
881 /* Make sure the file object knows it has an extension */
882 FileObject->Flags |= FO_FILE_OBJECT_HAS_EXTENSION;
883
884 FileObjectExtension = (PFILE_OBJECT_EXTENSION)(FileObject + 1);
885 FileObject->FileObjectExtension = FileObjectExtension;
886
887 /* Add the top level device which we'll send the request to */
888 if (OpenPacket->InternalFlags & IOP_USE_TOP_LEVEL_DEVICE_HINT)
889 {
890 FileObjectExtension->TopDeviceObjectHint = DeviceObject;
891 }
892 }
893 }
894 else
895 {
896 /* Use the dummy object instead */
897 LocalFileObject = OpenPacket->LocalFileObject;
898 RtlZeroMemory(LocalFileObject, sizeof(DUMMY_FILE_OBJECT));
899
900 /* Set it up */
901 FileObject = (PFILE_OBJECT)&LocalFileObject->ObjectHeader.Body;
902 LocalFileObject->ObjectHeader.Type = IoFileObjectType;
903 LocalFileObject->ObjectHeader.PointerCount = 1;
904 }
905
906 /* Setup the file header */
907 FileObject->Type = IO_TYPE_FILE;
908 FileObject->Size = sizeof(FILE_OBJECT);
909 FileObject->RelatedFileObject = OpenPacket->RelatedFileObject;
910 FileObject->DeviceObject = OriginalDeviceObject;
911
912 /* Check if this is a direct device open */
913 if (DirectOpen) FileObject->Flags |= FO_DIRECT_DEVICE_OPEN;
914
915 /* Check if the caller wants case sensitivity */
916 if (!(Attributes & OBJ_CASE_INSENSITIVE))
917 {
918 /* Tell the driver about it */
919 FileObject->Flags |= FO_OPENED_CASE_SENSITIVE;
920 }
921
922 /* Now set the file object */
923 Irp->Tail.Overlay.OriginalFileObject = FileObject;
924 StackLoc->FileObject = FileObject;
925
926 /* Check if the file object has a name */
927 if (RemainingName->Length)
928 {
929 /* Setup the unicode string */
930 FileObject->FileName.MaximumLength = RemainingName->Length +
931 sizeof(WCHAR);
932 FileObject->FileName.Buffer = ExAllocatePoolWithTag(PagedPool,
933 FileObject->
934 FileName.
935 MaximumLength,
936 TAG_IO_NAME);
937 if (!FileObject->FileName.Buffer)
938 {
939 /* Failed to allocate the name, free the IRP */
940 IoFreeIrp(Irp);
941
942 /* Dereference the device object and VPB */
943 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
944 if (Vpb) IopDereferenceVpbAndFree(Vpb);
945
946 /* Clear the FO and dereference it */
947 FileObject->DeviceObject = NULL;
948 if (!UseDummyFile) ObDereferenceObject(FileObject);
949
950 /* Fail */
951 return STATUS_INSUFFICIENT_RESOURCES;
952 }
953 }
954
955 /* Copy the name */
956 RtlCopyUnicodeString(&FileObject->FileName, RemainingName);
957
958 /* Initialize the File Object event and set the FO */
959 KeInitializeEvent(&FileObject->Event, NotificationEvent, FALSE);
960 OpenPacket->FileObject = FileObject;
961
962 /* Queue the IRP and call the driver */
963 IopQueueIrpToThread(Irp);
964 Status = IoCallDriver(DeviceObject, Irp);
965 if (Status == STATUS_PENDING)
966 {
967 /* Wait for the driver to complete the create */
968 KeWaitForSingleObject(&FileObject->Event,
969 Executive,
970 KernelMode,
971 FALSE,
972 NULL);
973
974 /* Get the new status */
975 Status = IoStatusBlock.Status;
976 }
977 else
978 {
979 /* We'll have to complete it ourselves */
980 ASSERT(!Irp->PendingReturned);
981 ASSERT(!Irp->MdlAddress);
982
983 /* Handle name change if required */
984 if (Status == STATUS_REPARSE)
985 {
986 /* Check this is a mount point */
987 if (Irp->IoStatus.Information == IO_REPARSE_TAG_MOUNT_POINT)
988 {
989 PREPARSE_DATA_BUFFER ReparseData;
990
991 /* Reparse point attributes were passed by the driver in the auxiliary buffer */
992 ASSERT(Irp->Tail.Overlay.AuxiliaryBuffer != NULL);
993 ReparseData = (PREPARSE_DATA_BUFFER)Irp->Tail.Overlay.AuxiliaryBuffer;
994
995 ASSERT(ReparseData->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT);
996 ASSERT(ReparseData->ReparseDataLength < MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
997 ASSERT(ReparseData->Reserved < MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
998
999 IopDoNameTransmogrify(Irp, FileObject, ReparseData);
1000 }
1001 }
1002
1003 /* Completion happens at APC_LEVEL */
1004 KeRaiseIrql(APC_LEVEL, &OldIrql);
1005
1006 /* Get the new I/O Status block ourselves */
1007 IoStatusBlock = Irp->IoStatus;
1008 Status = IoStatusBlock.Status;
1009
1010 /* Manually signal the even, we can't have any waiters */
1011 FileObject->Event.Header.SignalState = 1;
1012
1013 /* Now that we've signaled the events, de-associate the IRP */
1014 IopUnQueueIrpFromThread(Irp);
1015
1016 /* Check if the IRP had an input buffer */
1017 if ((Irp->Flags & IRP_BUFFERED_IO) &&
1018 (Irp->Flags & IRP_DEALLOCATE_BUFFER))
1019 {
1020 /* Free it. A driver might've tacked one on */
1021 ExFreePool(Irp->AssociatedIrp.SystemBuffer);
1022 }
1023
1024 /* Free the IRP and bring the IRQL back down */
1025 IoFreeIrp(Irp);
1026 KeLowerIrql(OldIrql);
1027 }
1028
1029 /* Copy the I/O Status */
1030 OpenPacket->Information = IoStatusBlock.Information;
1031
1032 /* The driver failed to create the file */
1033 if (!NT_SUCCESS(Status))
1034 {
1035 /* Check if we have a name */
1036 if (FileObject->FileName.Length)
1037 {
1038 /* Free it */
1039 ExFreePoolWithTag(FileObject->FileName.Buffer, TAG_IO_NAME);
1040 FileObject->FileName.Length = 0;
1041 }
1042
1043 /* Clear its device object */
1044 FileObject->DeviceObject = NULL;
1045
1046 /* Save this now because the FO might go away */
1047 OpenCancelled = FileObject->Flags & FO_FILE_OPEN_CANCELLED ?
1048 TRUE : FALSE;
1049
1050 /* Clear the file object in the open packet */
1051 OpenPacket->FileObject = NULL;
1052
1053 /* Dereference the file object */
1054 if (!UseDummyFile) ObDereferenceObject(FileObject);
1055
1056 /* Dereference the device object */
1057 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
1058
1059 /* Unless the driver cancelled the open, dereference the VPB */
1060 if (!(OpenCancelled) && (Vpb)) IopDereferenceVpbAndFree(Vpb);
1061
1062 /* Set the status and return */
1063 OpenPacket->FinalStatus = Status;
1064 return Status;
1065 }
1066 else if (Status == STATUS_REPARSE)
1067 {
1068 if (OpenPacket->Information == IO_REPARSE ||
1069 OpenPacket->Information == IO_REPARSE_TAG_MOUNT_POINT)
1070 {
1071 /* Update CompleteName with reparse info which got updated in IopDoNameTransmogrify() */
1072 if (CompleteName->MaximumLength < FileObject->FileName.Length)
1073 {
1074 PWSTR NewCompleteName;
1075
1076 /* Allocate a new buffer for the string */
1077 NewCompleteName = ExAllocatePoolWithTag(PagedPool, FileObject->FileName.Length, TAG_IO_NAME);
1078 if (NewCompleteName == NULL)
1079 {
1080 OpenPacket->FinalStatus = STATUS_INSUFFICIENT_RESOURCES;
1081 return STATUS_INSUFFICIENT_RESOURCES;
1082 }
1083
1084 /* Release the old one */
1085 if (CompleteName->Buffer != NULL)
1086 {
1087 ExFreePoolWithTag(CompleteName->Buffer, 0);
1088 }
1089
1090 /* And setup the new one */
1091 CompleteName->Buffer = NewCompleteName;
1092 CompleteName->MaximumLength = FileObject->FileName.Length;
1093 }
1094
1095 /* Copy our new complete name */
1096 RtlCopyUnicodeString(CompleteName, &FileObject->FileName);
1097
1098 if (OpenPacket->Information == IO_REPARSE_TAG_MOUNT_POINT)
1099 {
1100 OpenPacket->RelatedFileObject = NULL;
1101 }
1102 }
1103
1104 /* Check if we have a name */
1105 if (FileObject->FileName.Length)
1106 {
1107 /* Free it */
1108 ExFreePoolWithTag(FileObject->FileName.Buffer, 0);
1109 FileObject->FileName.Length = 0;
1110 }
1111
1112 /* Clear its device object */
1113 FileObject->DeviceObject = NULL;
1114
1115 /* Clear the file object in the open packet */
1116 OpenPacket->FileObject = NULL;
1117
1118 /* Dereference the file object */
1119 if (!UseDummyFile) ObDereferenceObject(FileObject);
1120
1121 /* Dereference the device object */
1122 IopDereferenceDeviceObject(OriginalDeviceObject, FALSE);
1123
1124 /* Unless the driver cancelled the open, dereference the VPB */
1125 if (Vpb != NULL) IopDereferenceVpbAndFree(Vpb);
1126
1127 if (OpenPacket->Information != IO_REMOUNT)
1128 {
1129 OpenPacket->RelatedFileObject = NULL;
1130
1131 /* Inform we traversed a mount point for later attempt */
1132 if (OpenPacket->Information == IO_REPARSE_TAG_MOUNT_POINT)
1133 {
1134 OpenPacket->TraversedMountPoint = 1;
1135 }
1136
1137 /* In case we override checks, but got this on volume open, fail hard */
1138 if (OpenPacket->Override)
1139 {
1140 KeBugCheckEx(DRIVER_RETURNED_STATUS_REPARSE_FOR_VOLUME_OPEN,
1141 (ULONG_PTR)OriginalDeviceObject,
1142 (ULONG_PTR)DeviceObject,
1143 (ULONG_PTR)CompleteName,
1144 OpenPacket->Information);
1145 }
1146
1147 /* Return to IO/OB so that information can be upgraded */
1148 return STATUS_REPARSE;
1149 }
1150
1151 /* Loop again and reattempt an opening */
1152 continue;
1153 }
1154
1155 break;
1156 }
1157
1158 if (Attempt == IOP_MAX_REPARSE_TRAVERSAL)
1159 return STATUS_UNSUCCESSFUL;
1160
1161 /* Get the owner of the File Object */
1162 OwnerDevice = IoGetRelatedDeviceObject(FileObject);
1163
1164 /*
1165 * It's possible that the device to whom we sent the IRP to
1166 * isn't actually the device that ended opening the file object
1167 * internally.
1168 */
1169 if (OwnerDevice != DeviceObject)
1170 {
1171 /* We have to de-reference the VPB we had associated */
1172 if (Vpb) IopDereferenceVpbAndFree(Vpb);
1173
1174 /* And re-associate with the actual one */
1175 Vpb = FileObject->Vpb;
1176 if (Vpb) InterlockedIncrement((PLONG)&Vpb->ReferenceCount);
1177 }
1178
1179 /* Make sure we are not using a dummy */
1180 if (!UseDummyFile)
1181 {
1182 /* Check if this was a volume open */
1183 if ((!(FileObject->RelatedFileObject) ||
1184 (FileObject->RelatedFileObject->Flags & FO_VOLUME_OPEN)) &&
1185 !(FileObject->FileName.Length))
1186 {
1187 /* All signs point to it, but make sure it was actually an FSD */
1188 if ((OwnerDevice->DeviceType == FILE_DEVICE_DISK_FILE_SYSTEM) ||
1189 (OwnerDevice->DeviceType == FILE_DEVICE_CD_ROM_FILE_SYSTEM) ||
1190 (OwnerDevice->DeviceType == FILE_DEVICE_TAPE_FILE_SYSTEM) ||
1191 (OwnerDevice->DeviceType == FILE_DEVICE_FILE_SYSTEM))
1192 {
1193 /* The owner device is an FSD, so this is a volume open for real */
1194 FileObject->Flags |= FO_VOLUME_OPEN;
1195 }
1196 }
1197
1198 /* Reference the object and set the parse check */
1199 ObReferenceObject(FileObject);
1200 *Object = FileObject;
1201 OpenPacket->FinalStatus = IoStatusBlock.Status;
1202 OpenPacket->ParseCheck = TRUE;
1203 return OpenPacket->FinalStatus;
1204 }
1205 else
1206 {
1207 /* Check if this was a query */
1208 if (OpenPacket->QueryOnly)
1209 {
1210 /* Check if the caller wants basic info only */
1211 if (!OpenPacket->FullAttributes)
1212 {
1213 /* Allocate the buffer */
1214 FileBasicInfo = ExAllocatePoolWithTag(NonPagedPool,
1215 sizeof(*FileBasicInfo),
1216 TAG_IO);
1217 if (FileBasicInfo)
1218 {
1219 /* Do the query */
1220 Status = IoQueryFileInformation(FileObject,
1221 FileBasicInformation,
1222 sizeof(*FileBasicInfo),
1223 FileBasicInfo,
1224 &ReturnLength);
1225 if (NT_SUCCESS(Status))
1226 {
1227 /* Copy the data */
1228 RtlCopyMemory(OpenPacket->BasicInformation,
1229 FileBasicInfo,
1230 ReturnLength);
1231 }
1232
1233 /* Free our buffer */
1234 ExFreePoolWithTag(FileBasicInfo, TAG_IO);
1235 }
1236 else
1237 {
1238 /* Fail */
1239 Status = STATUS_INSUFFICIENT_RESOURCES;
1240 }
1241 }
1242 else
1243 {
1244 /* This is a full query */
1245 Status = IoQueryFileInformation(
1246 FileObject,
1247 FileNetworkOpenInformation,
1248 sizeof(FILE_NETWORK_OPEN_INFORMATION),
1249 OpenPacket->NetworkInformation,
1250 &ReturnLength);
1251 if (!NT_SUCCESS(Status)) ASSERT(Status != STATUS_NOT_IMPLEMENTED);
1252 }
1253 }
1254
1255 /* Delete the file object */
1256 IopDeleteFile(FileObject);
1257
1258 /* Clear out the file */
1259 OpenPacket->FileObject = NULL;
1260
1261 /* Set and return status */
1262 OpenPacket->FinalStatus = Status;
1263 OpenPacket->ParseCheck = TRUE;
1264 return Status;
1265 }
1266 }
1267
1268 NTSTATUS
1269 NTAPI
1270 IopParseFile(IN PVOID ParseObject,
1271 IN PVOID ObjectType,
1272 IN OUT PACCESS_STATE AccessState,
1273 IN KPROCESSOR_MODE AccessMode,
1274 IN ULONG Attributes,
1275 IN OUT PUNICODE_STRING CompleteName,
1276 IN OUT PUNICODE_STRING RemainingName,
1277 IN OUT PVOID Context OPTIONAL,
1278 IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL,
1279 OUT PVOID *Object)
1280 {
1281 PVOID DeviceObject;
1282 POPEN_PACKET OpenPacket = (POPEN_PACKET)Context;
1283
1284 /* Validate the open packet */
1285 if (!IopValidateOpenPacket(OpenPacket)) return STATUS_OBJECT_TYPE_MISMATCH;
1286
1287 /* Get the device object */
1288 DeviceObject = IoGetRelatedDeviceObject(ParseObject);
1289 OpenPacket->RelatedFileObject = ParseObject;
1290
1291 /* Call the main routine */
1292 return IopParseDevice(DeviceObject,
1293 ObjectType,
1294 AccessState,
1295 AccessMode,
1296 Attributes,
1297 CompleteName,
1298 RemainingName,
1299 OpenPacket,
1300 SecurityQos,
1301 Object);
1302 }
1303
1304 VOID
1305 NTAPI
1306 IopDeleteFile(IN PVOID ObjectBody)
1307 {
1308 PFILE_OBJECT FileObject = (PFILE_OBJECT)ObjectBody;
1309 PIRP Irp;
1310 PIO_STACK_LOCATION StackPtr;
1311 NTSTATUS Status;
1312 KEVENT Event;
1313 PDEVICE_OBJECT DeviceObject;
1314 BOOLEAN DereferenceDone = FALSE;
1315 PVPB Vpb;
1316 KIRQL OldIrql;
1317 IOTRACE(IO_FILE_DEBUG, "ObjectBody: %p\n", ObjectBody);
1318
1319 /* Check if the file has a device object */
1320 if (FileObject->DeviceObject)
1321 {
1322 /* Check if this is a direct open or not */
1323 if (FileObject->Flags & FO_DIRECT_DEVICE_OPEN)
1324 {
1325 /* Get the attached device */
1326 DeviceObject = IoGetAttachedDevice(FileObject->DeviceObject);
1327 }
1328 else
1329 {
1330 /* Use the file object's device object */
1331 DeviceObject = IoGetRelatedDeviceObject(FileObject);
1332 }
1333
1334 /* Sanity check */
1335 ASSERT(!(FileObject->Flags & FO_SYNCHRONOUS_IO) ||
1336 (InterlockedExchange((PLONG)&FileObject->Busy, TRUE) == FALSE));
1337
1338 /* Check if the handle wasn't created yet */
1339 if (!(FileObject->Flags & FO_HANDLE_CREATED))
1340 {
1341 /* Send the cleanup IRP */
1342 IopCloseFile(NULL, ObjectBody, 0, 1, 1);
1343 }
1344
1345 /* Clear and set up Events */
1346 KeClearEvent(&FileObject->Event);
1347 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
1348
1349 /* Allocate an IRP */
1350 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
1351
1352 /* Set it up */
1353 Irp->UserEvent = &Event;
1354 Irp->UserIosb = &Irp->IoStatus;
1355 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
1356 Irp->Tail.Overlay.OriginalFileObject = FileObject;
1357 Irp->Flags = IRP_CLOSE_OPERATION | IRP_SYNCHRONOUS_API;
1358
1359 /* Set up Stack Pointer Data */
1360 StackPtr = IoGetNextIrpStackLocation(Irp);
1361 StackPtr->MajorFunction = IRP_MJ_CLOSE;
1362 StackPtr->FileObject = FileObject;
1363
1364 /* Queue the IRP */
1365 IopQueueIrpToThread(Irp);
1366
1367 /* Get the VPB and check if this isn't a direct open */
1368 Vpb = FileObject->Vpb;
1369 if ((Vpb) && !(FileObject->Flags & FO_DIRECT_DEVICE_OPEN))
1370 {
1371 /* Dereference the VPB before the close */
1372 InterlockedDecrement((PLONG)&Vpb->ReferenceCount);
1373 }
1374
1375 /* Check if the FS will never disappear by itself */
1376 if (FileObject->DeviceObject->Flags & DO_NEVER_LAST_DEVICE)
1377 {
1378 /* Dereference it */
1379 InterlockedDecrement(&FileObject->DeviceObject->ReferenceCount);
1380 DereferenceDone = TRUE;
1381 }
1382
1383 /* Call the FS Driver */
1384 Status = IoCallDriver(DeviceObject, Irp);
1385 if (Status == STATUS_PENDING)
1386 {
1387 /* Wait for completion */
1388 KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
1389 }
1390
1391 /* De-queue the IRP */
1392 KeRaiseIrql(APC_LEVEL, &OldIrql);
1393 IopUnQueueIrpFromThread(Irp);
1394 KeLowerIrql(OldIrql);
1395
1396 /* Free the IRP */
1397 IoFreeIrp(Irp);
1398
1399 /* Clear the file name */
1400 if (FileObject->FileName.Buffer)
1401 {
1402 ExFreePoolWithTag(FileObject->FileName.Buffer, TAG_IO_NAME);
1403 FileObject->FileName.Buffer = NULL;
1404 }
1405
1406 /* Check if the FO had a completion port */
1407 if (FileObject->CompletionContext)
1408 {
1409 /* Free it */
1410 ObDereferenceObject(FileObject->CompletionContext->Port);
1411 ExFreePool(FileObject->CompletionContext);
1412 }
1413
1414 /* Check if the FO had extension */
1415 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
1416 {
1417 /* Release filter context structure if any */
1418 FsRtlPTeardownPerFileObjectContexts(FileObject);
1419 }
1420
1421 /* Check if dereference has been done yet */
1422 if (!DereferenceDone)
1423 {
1424 /* Dereference device object */
1425 IopDereferenceDeviceObject(FileObject->DeviceObject, FALSE);
1426 }
1427 }
1428 }
1429
1430 PDEVICE_OBJECT
1431 NTAPI
1432 IopGetDeviceAttachmentBase(IN PDEVICE_OBJECT DeviceObject)
1433 {
1434 PDEVICE_OBJECT PDO = DeviceObject;
1435
1436 /* Go down the stack to attempt to get the PDO */
1437 for (; ((PEXTENDED_DEVOBJ_EXTENSION)PDO->DeviceObjectExtension)->AttachedTo != NULL;
1438 PDO = ((PEXTENDED_DEVOBJ_EXTENSION)PDO->DeviceObjectExtension)->AttachedTo);
1439
1440 return PDO;
1441 }
1442
1443 PDEVICE_OBJECT
1444 NTAPI
1445 IopGetDevicePDO(IN PDEVICE_OBJECT DeviceObject)
1446 {
1447 KIRQL OldIrql;
1448 PDEVICE_OBJECT PDO;
1449
1450 ASSERT(DeviceObject != NULL);
1451
1452 OldIrql = KeAcquireQueuedSpinLock(LockQueueIoDatabaseLock);
1453 /* Get the base DO */
1454 PDO = IopGetDeviceAttachmentBase(DeviceObject);
1455 /* Check whether that's really a PDO and if so, keep it */
1456 if ((PDO->Flags & DO_BUS_ENUMERATED_DEVICE) != DO_BUS_ENUMERATED_DEVICE)
1457 {
1458 PDO = NULL;
1459 }
1460 else
1461 {
1462 ObReferenceObject(PDO);
1463 }
1464 KeReleaseQueuedSpinLock(LockQueueIoDatabaseLock, OldIrql);
1465
1466 return PDO;
1467 }
1468
1469 NTSTATUS
1470 NTAPI
1471 IopSetDeviceSecurityDescriptor(IN PDEVICE_OBJECT DeviceObject,
1472 IN PSECURITY_INFORMATION SecurityInformation,
1473 IN PSECURITY_DESCRIPTOR SecurityDescriptor,
1474 IN POOL_TYPE PoolType,
1475 IN PGENERIC_MAPPING GenericMapping)
1476 {
1477 NTSTATUS Status;
1478 PSECURITY_DESCRIPTOR OldSecurityDescriptor, CachedSecurityDescriptor, NewSecurityDescriptor;
1479
1480 PAGED_CODE();
1481
1482 /* Keep attempting till we find our old SD or fail */
1483 while (TRUE)
1484 {
1485 KeEnterCriticalRegion();
1486 ExAcquireResourceSharedLite(&IopSecurityResource, TRUE);
1487
1488 /* Get our old SD and reference it */
1489 OldSecurityDescriptor = DeviceObject->SecurityDescriptor;
1490 if (OldSecurityDescriptor != NULL)
1491 {
1492 ObReferenceSecurityDescriptor(OldSecurityDescriptor, 1);
1493 }
1494
1495 ExReleaseResourceLite(&IopSecurityResource);
1496 KeLeaveCriticalRegion();
1497
1498 /* Set the SD information */
1499 NewSecurityDescriptor = OldSecurityDescriptor;
1500 Status = SeSetSecurityDescriptorInfo(NULL, SecurityInformation,
1501 SecurityDescriptor, &NewSecurityDescriptor,
1502 PoolType, GenericMapping);
1503
1504 if (!NT_SUCCESS(Status))
1505 {
1506 if (OldSecurityDescriptor != NULL)
1507 {
1508 ObDereferenceSecurityDescriptor(OldSecurityDescriptor, 1);
1509 }
1510
1511 break;
1512 }
1513
1514 /* Add the new DS to the internal cache */
1515 Status = ObLogSecurityDescriptor(NewSecurityDescriptor,
1516 &CachedSecurityDescriptor, 1);
1517 ExFreePool(NewSecurityDescriptor);
1518 if (!NT_SUCCESS(Status))
1519 {
1520 ObDereferenceSecurityDescriptor(OldSecurityDescriptor, 1);
1521 break;
1522 }
1523
1524 KeEnterCriticalRegion();
1525 ExAcquireResourceExclusiveLite(&IopSecurityResource, TRUE);
1526 /* Check if someone changed it in our back */
1527 if (DeviceObject->SecurityDescriptor == OldSecurityDescriptor)
1528 {
1529 /* We're clear, do the swap */
1530 DeviceObject->SecurityDescriptor = CachedSecurityDescriptor;
1531 ExReleaseResourceLite(&IopSecurityResource);
1532 KeLeaveCriticalRegion();
1533
1534 /* And dereference old SD (twice - us + not in use) */
1535 ObDereferenceSecurityDescriptor(OldSecurityDescriptor, 2);
1536
1537 break;
1538 }
1539 ExReleaseResourceLite(&IopSecurityResource);
1540 KeLeaveCriticalRegion();
1541
1542 /* If so, try again */
1543 ObDereferenceSecurityDescriptor(OldSecurityDescriptor, 1);
1544 ObDereferenceSecurityDescriptor(CachedSecurityDescriptor, 1);
1545 }
1546
1547 return Status;
1548 }
1549
1550 NTSTATUS
1551 NTAPI
1552 IopSetDeviceSecurityDescriptors(IN PDEVICE_OBJECT UpperDeviceObject,
1553 IN PDEVICE_OBJECT PhysicalDeviceObject,
1554 IN PSECURITY_INFORMATION SecurityInformation,
1555 IN PSECURITY_DESCRIPTOR SecurityDescriptor,
1556 IN POOL_TYPE PoolType,
1557 IN PGENERIC_MAPPING GenericMapping)
1558 {
1559 PDEVICE_OBJECT CurrentDO = PhysicalDeviceObject, NextDevice;
1560 NTSTATUS Status = STATUS_SUCCESS, TmpStatus;
1561
1562 PAGED_CODE();
1563
1564 ASSERT(PhysicalDeviceObject != NULL);
1565
1566 /* We always reference the DO we're working on */
1567 ObReferenceObject(CurrentDO);
1568
1569 /* Go up from PDO to latest DO */
1570 do
1571 {
1572 /* Attempt to set the new SD on it */
1573 TmpStatus = IopSetDeviceSecurityDescriptor(CurrentDO, SecurityInformation,
1574 SecurityDescriptor, PoolType,
1575 GenericMapping);
1576 /* Was our last one? Remember that status then */
1577 if (CurrentDO == UpperDeviceObject)
1578 {
1579 Status = TmpStatus;
1580 }
1581
1582 /* Try to move to the next DO (and thus, reference it) */
1583 NextDevice = CurrentDO->AttachedDevice;
1584 if (NextDevice)
1585 {
1586 ObReferenceObject(NextDevice);
1587 }
1588
1589 /* Dereference current DO and move to the next one */
1590 ObDereferenceObject(CurrentDO);
1591 CurrentDO = NextDevice;
1592 }
1593 while (CurrentDO != NULL);
1594
1595 return Status;
1596 }
1597
1598 NTSTATUS
1599 NTAPI
1600 IopGetSetSecurityObject(IN PVOID ObjectBody,
1601 IN SECURITY_OPERATION_CODE OperationCode,
1602 IN PSECURITY_INFORMATION SecurityInformation,
1603 IN PSECURITY_DESCRIPTOR SecurityDescriptor,
1604 IN OUT PULONG BufferLength,
1605 IN OUT PSECURITY_DESCRIPTOR *OldSecurityDescriptor,
1606 IN POOL_TYPE PoolType,
1607 IN OUT PGENERIC_MAPPING GenericMapping)
1608 {
1609 IO_STATUS_BLOCK IoStatusBlock;
1610 PIO_STACK_LOCATION StackPtr;
1611 PFILE_OBJECT FileObject;
1612 PDEVICE_OBJECT DeviceObject;
1613 PIRP Irp;
1614 BOOLEAN LocalEvent = FALSE;
1615 KEVENT Event;
1616 NTSTATUS Status = STATUS_SUCCESS;
1617 PAGED_CODE();
1618 IOTRACE(IO_FILE_DEBUG, "ObjectBody: %p\n", ObjectBody);
1619
1620 /* Check if this is a device or file */
1621 if (((PFILE_OBJECT)ObjectBody)->Type == IO_TYPE_DEVICE)
1622 {
1623 /* It's a device */
1624 DeviceObject = (PDEVICE_OBJECT)ObjectBody;
1625 FileObject = NULL;
1626 }
1627 else
1628 {
1629 /* It's a file */
1630 FileObject = (PFILE_OBJECT)ObjectBody;
1631
1632 /* Check if this is a direct open */
1633 if (FileObject->Flags & FO_DIRECT_DEVICE_OPEN)
1634 {
1635 /* Get the Device Object */
1636 DeviceObject = IoGetAttachedDevice(FileObject->DeviceObject);
1637 }
1638 else
1639 {
1640 /* Otherwise, use the direct device*/
1641 DeviceObject = FileObject->DeviceObject;
1642 }
1643 }
1644
1645 /* Check if the request was for a device object */
1646 if (!(FileObject) ||
1647 (!(FileObject->FileName.Length) && !(FileObject->RelatedFileObject)) ||
1648 (FileObject->Flags & FO_DIRECT_DEVICE_OPEN))
1649 {
1650 /* Check what kind of request this was */
1651 if (OperationCode == QuerySecurityDescriptor)
1652 {
1653 return SeQuerySecurityDescriptorInfo(SecurityInformation,
1654 SecurityDescriptor,
1655 BufferLength,
1656 &DeviceObject->SecurityDescriptor);
1657 }
1658 else if (OperationCode == DeleteSecurityDescriptor)
1659 {
1660 /* Simply return success */
1661 return STATUS_SUCCESS;
1662 }
1663 else if (OperationCode == AssignSecurityDescriptor)
1664 {
1665 Status = STATUS_SUCCESS;
1666
1667 /* Make absolutely sure this is a device object */
1668 if (!(FileObject) || !(FileObject->Flags & FO_STREAM_FILE))
1669 {
1670 PSECURITY_DESCRIPTOR CachedSecurityDescriptor;
1671
1672 /* Add the security descriptor in cache */
1673 Status = ObLogSecurityDescriptor(SecurityDescriptor, &CachedSecurityDescriptor, 1);
1674 if (NT_SUCCESS(Status))
1675 {
1676 KeEnterCriticalRegion();
1677 ExAcquireResourceExclusiveLite(&IopSecurityResource, TRUE);
1678
1679 /* Assign the Security Descriptor */
1680 DeviceObject->SecurityDescriptor = CachedSecurityDescriptor;
1681
1682 ExReleaseResourceLite(&IopSecurityResource);
1683 KeLeaveCriticalRegion();
1684 }
1685 }
1686
1687 /* Return status */
1688 return Status;
1689 }
1690 else if (OperationCode == SetSecurityDescriptor)
1691 {
1692 /* Get the Physical Device Object if any */
1693 PDEVICE_OBJECT PDO = IopGetDevicePDO(DeviceObject);
1694
1695 if (PDO != NULL)
1696 {
1697 /* Apply the new SD to any DO in the path from PDO to current DO */
1698 Status = IopSetDeviceSecurityDescriptors(DeviceObject, PDO,
1699 SecurityInformation,
1700 SecurityDescriptor,
1701 PoolType, GenericMapping);
1702 ObDereferenceObject(PDO);
1703 }
1704 else
1705 {
1706 /* Otherwise, just set for ourselves */
1707 Status = IopSetDeviceSecurityDescriptor(DeviceObject,
1708 SecurityInformation,
1709 SecurityDescriptor,
1710 PoolType, GenericMapping);
1711 }
1712
1713 return STATUS_SUCCESS;
1714 }
1715
1716 /* Shouldn't happen */
1717 return STATUS_SUCCESS;
1718 }
1719 else if (OperationCode == DeleteSecurityDescriptor)
1720 {
1721 /* Same as for devices, do nothing */
1722 return STATUS_SUCCESS;
1723 }
1724
1725 /* At this point, we know we're a file. Reference it */
1726 ObReferenceObject(FileObject);
1727
1728 /* Check if we should use Sync IO or not */
1729 if (FileObject->Flags & FO_SYNCHRONOUS_IO)
1730 {
1731 /* Lock the file object */
1732 Status = IopLockFileObject(FileObject, ExGetPreviousMode());
1733 if (Status != STATUS_SUCCESS)
1734 {
1735 ObDereferenceObject(FileObject);
1736 return Status;
1737 }
1738 }
1739 else
1740 {
1741 /* Use local event */
1742 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
1743 LocalEvent = TRUE;
1744 }
1745
1746 /* Clear the File Object event */
1747 KeClearEvent(&FileObject->Event);
1748
1749 /* Get the device object */
1750 DeviceObject = IoGetRelatedDeviceObject(FileObject);
1751
1752 /* Allocate the IRP */
1753 Irp = IoAllocateIrp(DeviceObject->StackSize, FALSE);
1754 if (!Irp) return IopCleanupFailedIrp(FileObject, NULL, NULL);
1755
1756 /* Set the IRP */
1757 Irp->Tail.Overlay.OriginalFileObject = FileObject;
1758 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
1759 Irp->RequestorMode = ExGetPreviousMode();
1760 Irp->UserIosb = &IoStatusBlock;
1761 Irp->UserEvent = (LocalEvent) ? &Event : NULL;
1762 Irp->Flags = (LocalEvent) ? IRP_SYNCHRONOUS_API : 0;
1763 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
1764
1765 /* Set Stack Parameters */
1766 StackPtr = IoGetNextIrpStackLocation(Irp);
1767 StackPtr->FileObject = FileObject;
1768
1769 /* Check if this is a query or set */
1770 if (OperationCode == QuerySecurityDescriptor)
1771 {
1772 /* Set the major function and parameters */
1773 StackPtr->MajorFunction = IRP_MJ_QUERY_SECURITY;
1774 StackPtr->Parameters.QuerySecurity.SecurityInformation =
1775 *SecurityInformation;
1776 StackPtr->Parameters.QuerySecurity.Length = *BufferLength;
1777 Irp->UserBuffer = SecurityDescriptor;
1778 }
1779 else
1780 {
1781 /* Set the major function and parameters for a set */
1782 StackPtr->MajorFunction = IRP_MJ_SET_SECURITY;
1783 StackPtr->Parameters.SetSecurity.SecurityInformation =
1784 *SecurityInformation;
1785 StackPtr->Parameters.SetSecurity.SecurityDescriptor =
1786 SecurityDescriptor;
1787 }
1788
1789 /* Queue the IRP */
1790 IopQueueIrpToThread(Irp);
1791
1792 /* Update operation counts */
1793 IopUpdateOperationCount(IopOtherTransfer);
1794
1795 /* Call the Driver */
1796 Status = IoCallDriver(DeviceObject, Irp);
1797
1798 /* Check if this was async I/O */
1799 if (LocalEvent)
1800 {
1801 /* Check if the IRP is pending completion */
1802 if (Status == STATUS_PENDING)
1803 {
1804 /* Wait on the local event */
1805 KeWaitForSingleObject(&Event,
1806 Executive,
1807 KernelMode,
1808 FALSE,
1809 NULL);
1810 Status = IoStatusBlock.Status;
1811 }
1812 }
1813 else
1814 {
1815 /* Check if the IRP is pending completion */
1816 if (Status == STATUS_PENDING)
1817 {
1818 /* Wait on the file object */
1819 KeWaitForSingleObject(&FileObject->Event,
1820 Executive,
1821 KernelMode,
1822 FALSE,
1823 NULL);
1824 Status = FileObject->FinalStatus;
1825 }
1826
1827 /* Release the lock */
1828 IopUnlockFileObject(FileObject);
1829 }
1830
1831 /* This Driver doesn't implement Security, so try to give it a default */
1832 if (Status == STATUS_INVALID_DEVICE_REQUEST)
1833 {
1834 /* Was this a query? */
1835 if (OperationCode == QuerySecurityDescriptor)
1836 {
1837 /* Set a World Security Descriptor */
1838 Status = SeSetWorldSecurityDescriptor(*SecurityInformation,
1839 SecurityDescriptor,
1840 BufferLength);
1841 }
1842 else
1843 {
1844 /* It wasn't a query, so just fake success */
1845 Status = STATUS_SUCCESS;
1846 }
1847 }
1848 else if (OperationCode == QuerySecurityDescriptor)
1849 {
1850 /* Callers usually expect the normalized form */
1851 if (Status == STATUS_BUFFER_OVERFLOW) Status = STATUS_BUFFER_TOO_SMALL;
1852
1853 _SEH2_TRY
1854 {
1855 /* Return length */
1856 *BufferLength = (ULONG)IoStatusBlock.Information;
1857 }
1858 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1859 {
1860 /* Get the exception code */
1861 Status = _SEH2_GetExceptionCode();
1862 }
1863 _SEH2_END;
1864 }
1865
1866 /* Return Status */
1867 return Status;
1868 }
1869
1870 NTSTATUS
1871 NTAPI
1872 IopQueryNameInternal(IN PVOID ObjectBody,
1873 IN BOOLEAN HasName,
1874 OUT POBJECT_NAME_INFORMATION ObjectNameInfo,
1875 IN ULONG Length,
1876 OUT PULONG ReturnLength,
1877 IN KPROCESSOR_MODE PreviousMode)
1878 {
1879 POBJECT_NAME_INFORMATION LocalInfo;
1880 PFILE_NAME_INFORMATION LocalFileInfo;
1881 PFILE_OBJECT FileObject = (PFILE_OBJECT)ObjectBody;
1882 ULONG LocalReturnLength, FileLength;
1883 BOOLEAN LengthMismatch = FALSE;
1884 NTSTATUS Status;
1885 PWCHAR p;
1886 IOTRACE(IO_FILE_DEBUG, "ObjectBody: %p\n", ObjectBody);
1887
1888 /* Validate length */
1889 if (Length < sizeof(OBJECT_NAME_INFORMATION))
1890 {
1891 /* Wrong length, fail */
1892 *ReturnLength = sizeof(OBJECT_NAME_INFORMATION);
1893 return STATUS_INFO_LENGTH_MISMATCH;
1894 }
1895
1896 /* Allocate Buffer */
1897 LocalInfo = ExAllocatePoolWithTag(PagedPool, Length, TAG_IO);
1898 if (!LocalInfo) return STATUS_INSUFFICIENT_RESOURCES;
1899
1900 /* Query the name */
1901 Status = ObQueryNameString(FileObject->DeviceObject,
1902 LocalInfo,
1903 Length,
1904 &LocalReturnLength);
1905 if (!NT_SUCCESS(Status) && (Status != STATUS_INFO_LENGTH_MISMATCH))
1906 {
1907 /* Free the buffer and fail */
1908 ExFreePoolWithTag(LocalInfo, TAG_IO);
1909 return Status;
1910 }
1911
1912 /* Copy the information */
1913 RtlCopyMemory(ObjectNameInfo,
1914 LocalInfo,
1915 (LocalReturnLength > Length) ?
1916 Length : LocalReturnLength);
1917
1918 /* Set buffer pointer */
1919 p = (PWCHAR)(ObjectNameInfo + 1);
1920 ObjectNameInfo->Name.Buffer = p;
1921
1922 /* Advance in buffer */
1923 p += (LocalInfo->Name.Length / sizeof(WCHAR));
1924
1925 /* Check if this already filled our buffer */
1926 if (LocalReturnLength > Length)
1927 {
1928 /* Set the length mismatch to true, so that we can return
1929 * the proper buffer size to the caller later
1930 */
1931 LengthMismatch = TRUE;
1932
1933 /* Save the initial buffer length value */
1934 *ReturnLength = LocalReturnLength;
1935 }
1936
1937 /* Now get the file name buffer and check the length needed */
1938 LocalFileInfo = (PFILE_NAME_INFORMATION)LocalInfo;
1939 FileLength = Length -
1940 LocalReturnLength +
1941 FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
1942
1943 /* Query the File name */
1944 if (PreviousMode == KernelMode &&
1945 BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
1946 {
1947 Status = IopGetFileInformation(FileObject,
1948 LengthMismatch ? Length : FileLength,
1949 FileNameInformation,
1950 LocalFileInfo,
1951 &LocalReturnLength);
1952 }
1953 else
1954 {
1955 Status = IoQueryFileInformation(FileObject,
1956 FileNameInformation,
1957 LengthMismatch ? Length : FileLength,
1958 LocalFileInfo,
1959 &LocalReturnLength);
1960 }
1961 if (NT_ERROR(Status))
1962 {
1963 /* Fail on errors only, allow warnings */
1964 ExFreePoolWithTag(LocalInfo, TAG_IO);
1965 return Status;
1966 }
1967
1968 /* If the provided buffer is too small, return the required size */
1969 if (LengthMismatch)
1970 {
1971 /* Add the required length */
1972 *ReturnLength += LocalFileInfo->FileNameLength;
1973
1974 /* Free the allocated buffer and return failure */
1975 ExFreePoolWithTag(LocalInfo, TAG_IO);
1976 return STATUS_BUFFER_OVERFLOW;
1977 }
1978
1979 /* Now calculate the new lengths left */
1980 FileLength = LocalReturnLength -
1981 FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
1982 LocalReturnLength = (ULONG)((ULONG_PTR)p -
1983 (ULONG_PTR)ObjectNameInfo +
1984 LocalFileInfo->FileNameLength);
1985
1986 /* Write the Name and null-terminate it */
1987 RtlCopyMemory(p, LocalFileInfo->FileName, FileLength);
1988 p += (FileLength / sizeof(WCHAR));
1989 *p = UNICODE_NULL;
1990 LocalReturnLength += sizeof(UNICODE_NULL);
1991
1992 /* Return the length needed */
1993 *ReturnLength = LocalReturnLength;
1994
1995 /* Setup the length and maximum length */
1996 FileLength = (ULONG)((ULONG_PTR)p - (ULONG_PTR)ObjectNameInfo);
1997 ObjectNameInfo->Name.Length = (USHORT)FileLength -
1998 sizeof(OBJECT_NAME_INFORMATION);
1999 ObjectNameInfo->Name.MaximumLength = (USHORT)ObjectNameInfo->Name.Length +
2000 sizeof(UNICODE_NULL);
2001
2002 /* Free buffer and return */
2003 ExFreePoolWithTag(LocalInfo, TAG_IO);
2004 return Status;
2005 }
2006
2007 VOID
2008 NTAPI
2009 IopCloseFile(IN PEPROCESS Process OPTIONAL,
2010 IN PVOID ObjectBody,
2011 IN ACCESS_MASK GrantedAccess,
2012 IN ULONG HandleCount,
2013 IN ULONG SystemHandleCount)
2014 {
2015 PFILE_OBJECT FileObject = (PFILE_OBJECT)ObjectBody;
2016 KEVENT Event;
2017 PIRP Irp;
2018 PIO_STACK_LOCATION StackPtr;
2019 NTSTATUS Status;
2020 PDEVICE_OBJECT DeviceObject;
2021 KIRQL OldIrql;
2022 IO_STATUS_BLOCK IoStatusBlock;
2023 IOTRACE(IO_FILE_DEBUG, "ObjectBody: %p\n", ObjectBody);
2024
2025 /* If this isn't the last handle for the current process, quit */
2026 if (HandleCount != 1) return;
2027
2028 /* Check if the file is locked and has more then one handle opened */
2029 if ((FileObject->LockOperation) && (SystemHandleCount != 1))
2030 {
2031 /* Check if this is a direct open or not */
2032 if (BooleanFlagOn(FileObject->Flags, FO_DIRECT_DEVICE_OPEN))
2033 {
2034 /* Get the attached device */
2035 DeviceObject = IoGetAttachedDevice(FileObject->DeviceObject);
2036 }
2037 else
2038 {
2039 /* Get the FO's device */
2040 DeviceObject = IoGetRelatedDeviceObject(FileObject);
2041 }
2042
2043 /* Check if this is a sync FO and lock it */
2044 if (BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2045 {
2046 (VOID)IopLockFileObject(FileObject, KernelMode);
2047 }
2048
2049 /* Go the FastIO path if possible, otherwise fall back to IRP */
2050 if (DeviceObject->DriverObject->FastIoDispatch == NULL ||
2051 DeviceObject->DriverObject->FastIoDispatch->FastIoUnlockAll == NULL ||
2052 !DeviceObject->DriverObject->FastIoDispatch->FastIoUnlockAll(FileObject, PsGetCurrentProcess(), &IoStatusBlock, DeviceObject))
2053 {
2054 /* Clear and set up Events */
2055 KeClearEvent(&FileObject->Event);
2056 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
2057
2058 /* Allocate an IRP */
2059 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
2060
2061 /* Set it up */
2062 Irp->UserEvent = &Event;
2063 Irp->UserIosb = &Irp->IoStatus;
2064 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
2065 Irp->Tail.Overlay.OriginalFileObject = FileObject;
2066 Irp->RequestorMode = KernelMode;
2067 Irp->Flags = IRP_SYNCHRONOUS_API;
2068 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
2069 ObReferenceObject(FileObject);
2070
2071 /* Set up Stack Pointer Data */
2072 StackPtr = IoGetNextIrpStackLocation(Irp);
2073 StackPtr->MajorFunction = IRP_MJ_LOCK_CONTROL;
2074 StackPtr->MinorFunction = IRP_MN_UNLOCK_ALL;
2075 StackPtr->FileObject = FileObject;
2076
2077 /* Queue the IRP */
2078 IopQueueIrpToThread(Irp);
2079
2080 /* Call the FS Driver */
2081 Status = IoCallDriver(DeviceObject, Irp);
2082 if (Status == STATUS_PENDING)
2083 {
2084 /* Wait for completion */
2085 KeWaitForSingleObject(&Event, UserRequest, KernelMode, FALSE, NULL);
2086 }
2087
2088 /* IO will unqueue & free for us */
2089 }
2090
2091 /* Release the lock if we were holding it */
2092 if (BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2093 {
2094 IopUnlockFileObject(FileObject);
2095 }
2096 }
2097
2098 /* Make sure this is the last handle */
2099 if (SystemHandleCount != 1) return;
2100
2101 /* Check if this is a direct open or not */
2102 if (FileObject->Flags & FO_DIRECT_DEVICE_OPEN)
2103 {
2104 /* Get the attached device */
2105 DeviceObject = IoGetAttachedDevice(FileObject->DeviceObject);
2106 }
2107 else
2108 {
2109 /* Get the FO's device */
2110 DeviceObject = IoGetRelatedDeviceObject(FileObject);
2111 }
2112
2113 /* Set the handle created flag */
2114 FileObject->Flags |= FO_HANDLE_CREATED;
2115
2116 /* Check if this is a sync FO and lock it */
2117 if (Process != NULL &&
2118 BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2119 {
2120 (VOID)IopLockFileObject(FileObject, KernelMode);
2121 }
2122
2123 /* Clear and set up Events */
2124 KeClearEvent(&FileObject->Event);
2125 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
2126
2127 /* Allocate an IRP */
2128 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
2129
2130 /* Set it up */
2131 Irp->UserEvent = &Event;
2132 Irp->UserIosb = &Irp->IoStatus;
2133 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
2134 Irp->Tail.Overlay.OriginalFileObject = FileObject;
2135 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
2136 Irp->Flags = IRP_CLOSE_OPERATION | IRP_SYNCHRONOUS_API;
2137
2138 /* Set up Stack Pointer Data */
2139 StackPtr = IoGetNextIrpStackLocation(Irp);
2140 StackPtr->MajorFunction = IRP_MJ_CLEANUP;
2141 StackPtr->FileObject = FileObject;
2142
2143 /* Queue the IRP */
2144 IopQueueIrpToThread(Irp);
2145
2146 /* Update operation counts */
2147 IopUpdateOperationCount(IopOtherTransfer);
2148
2149 /* Call the FS Driver */
2150 Status = IoCallDriver(DeviceObject, Irp);
2151 if (Status == STATUS_PENDING)
2152 {
2153 /* Wait for completion */
2154 KeWaitForSingleObject(&Event, UserRequest, KernelMode, FALSE, NULL);
2155 }
2156
2157 /* Unqueue the IRP */
2158 KeRaiseIrql(APC_LEVEL, &OldIrql);
2159 IopUnQueueIrpFromThread(Irp);
2160 KeLowerIrql(OldIrql);
2161
2162 /* Free the IRP */
2163 IoFreeIrp(Irp);
2164
2165 /* Release the lock if we were holding it */
2166 if (Process != NULL &&
2167 BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2168 {
2169 IopUnlockFileObject(FileObject);
2170 }
2171 }
2172
2173 NTSTATUS
2174 NTAPI
2175 IopQueryAttributesFile(IN POBJECT_ATTRIBUTES ObjectAttributes,
2176 IN FILE_INFORMATION_CLASS FileInformationClass,
2177 IN ULONG FileInformationSize,
2178 OUT PVOID FileInformation)
2179 {
2180 NTSTATUS Status;
2181 KPROCESSOR_MODE AccessMode = ExGetPreviousMode();
2182 DUMMY_FILE_OBJECT LocalFileObject;
2183 FILE_NETWORK_OPEN_INFORMATION NetworkOpenInfo;
2184 HANDLE Handle;
2185 OPEN_PACKET OpenPacket;
2186 BOOLEAN IsBasic;
2187 PAGED_CODE();
2188 IOTRACE(IO_FILE_DEBUG, "Class: %lx\n", FileInformationClass);
2189
2190 /* Check if the caller was user mode */
2191 if (AccessMode != KernelMode)
2192 {
2193 /* Protect probe in SEH */
2194 _SEH2_TRY
2195 {
2196 /* Probe the buffer */
2197 ProbeForWrite(FileInformation, FileInformationSize, sizeof(ULONG));
2198 }
2199 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2200 {
2201 /* Return the exception code */
2202 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2203 }
2204 _SEH2_END;
2205 }
2206
2207 /* Check if this is a basic or full request */
2208 IsBasic = (FileInformationSize == sizeof(FILE_BASIC_INFORMATION));
2209
2210 /* Setup the Open Packet */
2211 RtlZeroMemory(&OpenPacket, sizeof(OPEN_PACKET));
2212 OpenPacket.Type = IO_TYPE_OPEN_PACKET;
2213 OpenPacket.Size = sizeof(OPEN_PACKET);
2214 OpenPacket.CreateOptions = FILE_OPEN_REPARSE_POINT;
2215 OpenPacket.ShareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
2216 OpenPacket.Disposition = FILE_OPEN;
2217 OpenPacket.BasicInformation = IsBasic ? FileInformation : NULL;
2218 OpenPacket.NetworkInformation = IsBasic ? &NetworkOpenInfo :
2219 (AccessMode != KernelMode) ?
2220 &NetworkOpenInfo : FileInformation;
2221 OpenPacket.QueryOnly = TRUE;
2222 OpenPacket.FullAttributes = IsBasic ? FALSE : TRUE;
2223 OpenPacket.LocalFileObject = &LocalFileObject;
2224
2225 /* Update the operation count */
2226 IopUpdateOperationCount(IopOtherTransfer);
2227
2228 /*
2229 * Attempt opening the file. This will call the I/O Parse Routine for
2230 * the File Object (IopParseDevice) which will use the dummy file obejct
2231 * send the IRP to its device object. Note that we have two statuses
2232 * to worry about: the Object Manager's status (in Status) and the I/O
2233 * status, which is in the Open Packet's Final Status, and determined
2234 * by the Parse Check member.
2235 */
2236 Status = ObOpenObjectByName(ObjectAttributes,
2237 NULL,
2238 AccessMode,
2239 NULL,
2240 FILE_READ_ATTRIBUTES,
2241 &OpenPacket,
2242 &Handle);
2243 if (OpenPacket.ParseCheck == FALSE)
2244 {
2245 /* Parse failed */
2246 DPRINT("IopQueryAttributesFile failed for '%wZ' with 0x%lx\n",
2247 ObjectAttributes->ObjectName, Status);
2248 return Status;
2249 }
2250 else
2251 {
2252 /* Use the Io status */
2253 Status = OpenPacket.FinalStatus;
2254 }
2255
2256 /* Check if we were succesful and this was user mode and a full query */
2257 if ((NT_SUCCESS(Status)) && (AccessMode != KernelMode) && !(IsBasic))
2258 {
2259 /* Enter SEH for copy */
2260 _SEH2_TRY
2261 {
2262 /* Copy the buffer back */
2263 RtlCopyMemory(FileInformation,
2264 &NetworkOpenInfo,
2265 FileInformationSize);
2266 }
2267 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2268 {
2269 /* Get exception code */
2270 Status = _SEH2_GetExceptionCode();
2271 }
2272 _SEH2_END;
2273 }
2274
2275 /* Return status */
2276 return Status;
2277 }
2278
2279 NTSTATUS
2280 NTAPI
2281 IopAcquireFileObjectLock(
2282 _In_ PFILE_OBJECT FileObject,
2283 _In_ KPROCESSOR_MODE WaitMode,
2284 _In_ BOOLEAN Alertable,
2285 _Out_ PBOOLEAN LockFailed)
2286 {
2287 NTSTATUS Status;
2288
2289 PAGED_CODE();
2290
2291 InterlockedIncrement((PLONG)&FileObject->Waiters);
2292
2293 Status = STATUS_SUCCESS;
2294 do
2295 {
2296 if (!InterlockedExchange((PLONG)&FileObject->Busy, TRUE))
2297 {
2298 break;
2299 }
2300 Status = KeWaitForSingleObject(&FileObject->Lock,
2301 Executive,
2302 WaitMode,
2303 Alertable,
2304 NULL);
2305 } while (Status == STATUS_SUCCESS);
2306
2307 InterlockedDecrement((PLONG)&FileObject->Waiters);
2308 if (Status == STATUS_SUCCESS)
2309 {
2310 ObReferenceObject(FileObject);
2311 *LockFailed = FALSE;
2312 }
2313 else
2314 {
2315 if (!FileObject->Busy && FileObject->Waiters)
2316 {
2317 KeSetEvent(&FileObject->Lock, IO_NO_INCREMENT, FALSE);
2318 }
2319 *LockFailed = TRUE;
2320 }
2321
2322 return Status;
2323 }
2324
2325 PVOID
2326 NTAPI
2327 IoGetFileObjectFilterContext(IN PFILE_OBJECT FileObject)
2328 {
2329 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
2330 {
2331 UNIMPLEMENTED;
2332 /* FIXME: return NULL for the moment ~ */
2333 return NULL;
2334 }
2335
2336 return NULL;
2337 }
2338
2339 NTSTATUS
2340 NTAPI
2341 IoChangeFileObjectFilterContext(IN PFILE_OBJECT FileObject,
2342 IN PVOID FilterContext,
2343 IN BOOLEAN Define)
2344 {
2345 if (!(FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION))
2346 {
2347 return STATUS_INVALID_PARAMETER;
2348 }
2349
2350 UNIMPLEMENTED;
2351
2352 return STATUS_NOT_IMPLEMENTED;
2353 }
2354
2355 NTSTATUS
2356 NTAPI
2357 IopCreateFile(OUT PHANDLE FileHandle,
2358 IN ACCESS_MASK DesiredAccess,
2359 IN POBJECT_ATTRIBUTES ObjectAttributes,
2360 OUT PIO_STATUS_BLOCK IoStatusBlock,
2361 IN PLARGE_INTEGER AllocationSize OPTIONAL,
2362 IN ULONG FileAttributes,
2363 IN ULONG ShareAccess,
2364 IN ULONG Disposition,
2365 IN ULONG CreateOptions,
2366 IN PVOID EaBuffer OPTIONAL,
2367 IN ULONG EaLength,
2368 IN CREATE_FILE_TYPE CreateFileType,
2369 IN PVOID ExtraCreateParameters OPTIONAL,
2370 IN ULONG Options,
2371 IN ULONG Flags,
2372 IN PDEVICE_OBJECT DeviceObject OPTIONAL)
2373 {
2374 KPROCESSOR_MODE AccessMode;
2375 HANDLE LocalHandle = 0;
2376 LARGE_INTEGER SafeAllocationSize;
2377 NTSTATUS Status = STATUS_SUCCESS;
2378 PNAMED_PIPE_CREATE_PARAMETERS NamedPipeCreateParameters;
2379 POPEN_PACKET OpenPacket;
2380 ULONG EaErrorOffset;
2381 PAGED_CODE();
2382
2383 IOTRACE(IO_FILE_DEBUG, "FileName: %wZ\n", ObjectAttributes->ObjectName);
2384
2385
2386 /* Check if we have no parameter checking to do */
2387 if (Options & IO_NO_PARAMETER_CHECKING)
2388 {
2389 /* Then force kernel-mode access to avoid checks */
2390 AccessMode = KernelMode;
2391 }
2392 else
2393 {
2394 /* Otherwise, use the actual mode */
2395 AccessMode = ExGetPreviousMode();
2396 }
2397
2398 /* Check if we need to do parameter checking */
2399 if ((AccessMode != KernelMode) || (Options & IO_CHECK_CREATE_PARAMETERS))
2400 {
2401 /* Validate parameters */
2402 if (FileAttributes & ~FILE_ATTRIBUTE_VALID_FLAGS)
2403 {
2404 DPRINT1("File Create 'FileAttributes' Parameter contains invalid flags!\n");
2405 return STATUS_INVALID_PARAMETER;
2406 }
2407
2408 if (ShareAccess & ~FILE_SHARE_VALID_FLAGS)
2409 {
2410 DPRINT1("File Create 'ShareAccess' Parameter contains invalid flags!\n");
2411 return STATUS_INVALID_PARAMETER;
2412 }
2413
2414 if (Disposition > FILE_MAXIMUM_DISPOSITION)
2415 {
2416 DPRINT1("File Create 'Disposition' Parameter is out of range!\n");
2417 return STATUS_INVALID_PARAMETER;
2418 }
2419
2420 if (CreateOptions & ~FILE_VALID_OPTION_FLAGS)
2421 {
2422 DPRINT1("File Create 'CreateOptions' parameter contains invalid flags!\n");
2423 return STATUS_INVALID_PARAMETER;
2424 }
2425
2426 if ((CreateOptions & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) &&
2427 (!(DesiredAccess & SYNCHRONIZE)))
2428 {
2429 DPRINT1("File Create 'CreateOptions' parameter FILE_SYNCHRONOUS_IO_* requested, but 'DesiredAccess' does not have SYNCHRONIZE!\n");
2430 return STATUS_INVALID_PARAMETER;
2431 }
2432
2433 if ((CreateOptions & FILE_DELETE_ON_CLOSE) && (!(DesiredAccess & DELETE)))
2434 {
2435 DPRINT1("File Create 'CreateOptions' parameter FILE_DELETE_ON_CLOSE requested, but 'DesiredAccess' does not have DELETE!\n");
2436 return STATUS_INVALID_PARAMETER;
2437 }
2438
2439 if ((CreateOptions & (FILE_SYNCHRONOUS_IO_NONALERT | FILE_SYNCHRONOUS_IO_ALERT)) ==
2440 (FILE_SYNCHRONOUS_IO_NONALERT | FILE_SYNCHRONOUS_IO_ALERT))
2441 {
2442 DPRINT1("File Create 'FileAttributes' parameter both FILE_SYNCHRONOUS_IO_NONALERT and FILE_SYNCHRONOUS_IO_ALERT specified!\n");
2443 return STATUS_INVALID_PARAMETER;
2444 }
2445
2446 if ((CreateOptions & FILE_DIRECTORY_FILE) && !(CreateOptions & FILE_NON_DIRECTORY_FILE) &&
2447 (CreateOptions & ~(FILE_DIRECTORY_FILE |
2448 FILE_SYNCHRONOUS_IO_ALERT |
2449 FILE_SYNCHRONOUS_IO_NONALERT |
2450 FILE_WRITE_THROUGH |
2451 FILE_COMPLETE_IF_OPLOCKED |
2452 FILE_OPEN_FOR_BACKUP_INTENT |
2453 FILE_DELETE_ON_CLOSE |
2454 FILE_OPEN_FOR_FREE_SPACE_QUERY |
2455 FILE_OPEN_BY_FILE_ID |
2456 FILE_NO_COMPRESSION |
2457 FILE_OPEN_REPARSE_POINT)))
2458 {
2459 DPRINT1("File Create 'CreateOptions' Parameter has flags incompatible with FILE_DIRECTORY_FILE!\n");
2460 return STATUS_INVALID_PARAMETER;
2461 }
2462
2463 if ((CreateOptions & FILE_DIRECTORY_FILE) && !(CreateOptions & FILE_NON_DIRECTORY_FILE) &&
2464 (Disposition != FILE_CREATE) && (Disposition != FILE_OPEN) && (Disposition != FILE_OPEN_IF))
2465 {
2466 DPRINT1("File Create 'CreateOptions' Parameter FILE_DIRECTORY_FILE requested, but 'Disposition' is not FILE_CREATE/FILE_OPEN/FILE_OPEN_IF!\n");
2467 return STATUS_INVALID_PARAMETER;
2468 }
2469
2470 if ((CreateOptions & FILE_COMPLETE_IF_OPLOCKED) && (CreateOptions & FILE_RESERVE_OPFILTER))
2471 {
2472 DPRINT1("File Create 'CreateOptions' Parameter both FILE_COMPLETE_IF_OPLOCKED and FILE_RESERVE_OPFILTER specified!\n");
2473 return STATUS_INVALID_PARAMETER;
2474 }
2475
2476 if ((CreateOptions & FILE_NO_INTERMEDIATE_BUFFERING) && (DesiredAccess & FILE_APPEND_DATA))
2477 {
2478 DPRINT1("File Create 'CreateOptions' parameter FILE_NO_INTERMEDIATE_BUFFERING requested, but 'DesiredAccess' FILE_APPEND_DATA requires it!\n");
2479 return STATUS_INVALID_PARAMETER;
2480 }
2481
2482 /* Now check if this is a named pipe */
2483 if (CreateFileType == CreateFileTypeNamedPipe)
2484 {
2485 /* Make sure we have extra parameters */
2486 if (!ExtraCreateParameters)
2487 {
2488 DPRINT1("Invalid parameter: ExtraCreateParameters == 0!\n");
2489 return STATUS_INVALID_PARAMETER;
2490 }
2491
2492 /* Get the parameters and validate them */
2493 NamedPipeCreateParameters = ExtraCreateParameters;
2494 if ((NamedPipeCreateParameters->NamedPipeType > FILE_PIPE_MESSAGE_TYPE) ||
2495 (NamedPipeCreateParameters->ReadMode > FILE_PIPE_MESSAGE_MODE) ||
2496 (NamedPipeCreateParameters->CompletionMode > FILE_PIPE_COMPLETE_OPERATION) ||
2497 (ShareAccess & FILE_SHARE_DELETE) ||
2498 ((Disposition < FILE_OPEN) || (Disposition > FILE_OPEN_IF)) ||
2499 (CreateOptions & ~FILE_VALID_PIPE_OPTION_FLAGS))
2500 {
2501 /* Invalid named pipe create */
2502 DPRINT1("Invalid named pipe create\n");
2503 return STATUS_INVALID_PARAMETER;
2504 }
2505 }
2506 else if (CreateFileType == CreateFileTypeMailslot)
2507 {
2508 /* Make sure we have extra parameters */
2509 if (!ExtraCreateParameters)
2510 {
2511 DPRINT1("Invalid parameter: ExtraCreateParameters == 0!\n");
2512 return STATUS_INVALID_PARAMETER;
2513 }
2514
2515 /* Get the parameters and validate them */
2516 if ((ShareAccess & FILE_SHARE_DELETE) ||
2517 !(ShareAccess & ~FILE_SHARE_WRITE) ||
2518 (Disposition != FILE_CREATE) ||
2519 (CreateOptions & ~FILE_VALID_MAILSLOT_OPTION_FLAGS))
2520 {
2521 /* Invalid mailslot create */
2522 DPRINT1("Invalid mailslot create\n");
2523 return STATUS_INVALID_PARAMETER;
2524 }
2525 }
2526 }
2527
2528 /* Allocate the open packet */
2529 OpenPacket = ExAllocatePoolWithTag(NonPagedPool, sizeof(*OpenPacket), 'pOoI');
2530 if (!OpenPacket) return STATUS_INSUFFICIENT_RESOURCES;
2531 RtlZeroMemory(OpenPacket, sizeof(*OpenPacket));
2532
2533 /* Check if the call came from user mode */
2534 if (AccessMode != KernelMode)
2535 {
2536 _SEH2_TRY
2537 {
2538 /* Probe the output parameters */
2539 ProbeForWriteHandle(FileHandle);
2540 ProbeForWriteIoStatusBlock(IoStatusBlock);
2541
2542 /* Probe the allocation size if one was passed in */
2543 if (AllocationSize)
2544 {
2545 SafeAllocationSize = ProbeForReadLargeInteger(AllocationSize);
2546 }
2547 else
2548 {
2549 SafeAllocationSize.QuadPart = 0;
2550 }
2551
2552 /* Make sure it's valid */
2553 if (SafeAllocationSize.QuadPart < 0)
2554 {
2555 RtlRaiseStatus(STATUS_INVALID_PARAMETER);
2556 }
2557
2558 /* Check if EA was passed in */
2559 if ((EaBuffer) && (EaLength))
2560 {
2561 /* Probe it */
2562 ProbeForRead(EaBuffer, EaLength, sizeof(ULONG));
2563
2564 /* And marshall it */
2565 OpenPacket->EaBuffer = ExAllocatePoolWithTag(NonPagedPool,
2566 EaLength,
2567 TAG_EA);
2568 OpenPacket->EaLength = EaLength;
2569 RtlCopyMemory(OpenPacket->EaBuffer, EaBuffer, EaLength);
2570
2571 /* Validate the buffer */
2572 Status = IoCheckEaBufferValidity(OpenPacket->EaBuffer,
2573 EaLength,
2574 &EaErrorOffset);
2575 if (!NT_SUCCESS(Status))
2576 {
2577 /* Undo everything if it's invalid */
2578 DPRINT1("Invalid EA buffer\n");
2579 IoStatusBlock->Status = Status;
2580 IoStatusBlock->Information = EaErrorOffset;
2581 RtlRaiseStatus(Status);
2582 }
2583 }
2584 }
2585 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2586 {
2587 /* Return the exception code */
2588 if (OpenPacket->EaBuffer != NULL) ExFreePool(OpenPacket->EaBuffer);
2589 ExFreePool(OpenPacket);
2590 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2591 }
2592 _SEH2_END;
2593 }
2594 else
2595 {
2596 /* Check if this is a device attach */
2597 if (CreateOptions & IO_ATTACH_DEVICE_API)
2598 {
2599 /* Set the flag properly */
2600 Options |= IO_ATTACH_DEVICE;
2601 CreateOptions &= ~IO_ATTACH_DEVICE_API;
2602 }
2603
2604 /* Check if we have allocation size */
2605 if (AllocationSize)
2606 {
2607 /* Capture it */
2608 SafeAllocationSize = *AllocationSize;
2609 }
2610 else
2611 {
2612 /* Otherwise, no size */
2613 SafeAllocationSize.QuadPart = 0;
2614 }
2615
2616 /* Check if we have an EA packet */
2617 if ((EaBuffer) && (EaLength))
2618 {
2619 /* Allocate the kernel copy */
2620 OpenPacket->EaBuffer = ExAllocatePoolWithTag(NonPagedPool,
2621 EaLength,
2622 TAG_EA);
2623 if (!OpenPacket->EaBuffer)
2624 {
2625 ExFreePool(OpenPacket);
2626 DPRINT1("Failed to allocate open packet EA buffer\n");
2627 return STATUS_INSUFFICIENT_RESOURCES;
2628 }
2629
2630 /* Copy the data */
2631 OpenPacket->EaLength = EaLength;
2632 RtlCopyMemory(OpenPacket->EaBuffer, EaBuffer, EaLength);
2633
2634 /* Validate the buffer */
2635 Status = IoCheckEaBufferValidity(OpenPacket->EaBuffer,
2636 EaLength,
2637 &EaErrorOffset);
2638 if (!NT_SUCCESS(Status))
2639 {
2640 /* Undo everything if it's invalid */
2641 DPRINT1("Invalid EA buffer\n");
2642 ExFreePool(OpenPacket->EaBuffer);
2643 IoStatusBlock->Status = Status;
2644 IoStatusBlock->Information = EaErrorOffset;
2645 ExFreePool(OpenPacket);
2646 return Status;
2647 }
2648 }
2649 }
2650
2651 /* Setup the Open Packet */
2652 OpenPacket->Type = IO_TYPE_OPEN_PACKET;
2653 OpenPacket->Size = sizeof(*OpenPacket);
2654 OpenPacket->AllocationSize = SafeAllocationSize;
2655 OpenPacket->CreateOptions = CreateOptions;
2656 OpenPacket->FileAttributes = (USHORT)FileAttributes;
2657 OpenPacket->ShareAccess = (USHORT)ShareAccess;
2658 OpenPacket->Options = Options;
2659 OpenPacket->Disposition = Disposition;
2660 OpenPacket->CreateFileType = CreateFileType;
2661 OpenPacket->ExtraCreateParameters = ExtraCreateParameters;
2662 OpenPacket->InternalFlags = Flags;
2663 OpenPacket->TopDeviceObjectHint = DeviceObject;
2664
2665 /* Update the operation count */
2666 IopUpdateOperationCount(IopOtherTransfer);
2667
2668 /*
2669 * Attempt opening the file. This will call the I/O Parse Routine for
2670 * the File Object (IopParseDevice) which will create the object and
2671 * send the IRP to its device object. Note that we have two statuses
2672 * to worry about: the Object Manager's status (in Status) and the I/O
2673 * status, which is in the Open Packet's Final Status, and determined
2674 * by the Parse Check member.
2675 */
2676 Status = ObOpenObjectByName(ObjectAttributes,
2677 NULL,
2678 AccessMode,
2679 NULL,
2680 DesiredAccess,
2681 OpenPacket,
2682 &LocalHandle);
2683
2684 /* Free the EA Buffer */
2685 if (OpenPacket->EaBuffer) ExFreePool(OpenPacket->EaBuffer);
2686
2687 /* Now check for Ob or Io failure */
2688 if (!(NT_SUCCESS(Status)) || (OpenPacket->ParseCheck == FALSE))
2689 {
2690 /* Check if Ob thinks well went well */
2691 if (NT_SUCCESS(Status))
2692 {
2693 /*
2694 * Tell it otherwise. Because we didn't use an ObjectType,
2695 * it incorrectly returned us a handle to God knows what.
2696 */
2697 ZwClose(LocalHandle);
2698 Status = STATUS_OBJECT_TYPE_MISMATCH;
2699 }
2700
2701 /* Now check the Io status */
2702 if (!NT_SUCCESS(OpenPacket->FinalStatus))
2703 {
2704 /* Use this status instead of Ob's */
2705 Status = OpenPacket->FinalStatus;
2706
2707 /* Check if it was only a warning */
2708 if (NT_WARNING(Status))
2709 {
2710 /* Protect write with SEH */
2711 _SEH2_TRY
2712 {
2713 /* In this case, we copy the I/O Status back */
2714 IoStatusBlock->Information = OpenPacket->Information;
2715 IoStatusBlock->Status = OpenPacket->FinalStatus;
2716 }
2717 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2718 {
2719 /* Get exception code */
2720 Status = _SEH2_GetExceptionCode();
2721 }
2722 _SEH2_END;
2723 }
2724 }
2725 else if ((OpenPacket->FileObject) && (OpenPacket->ParseCheck == FALSE))
2726 {
2727 /*
2728 * This can happen in the very bizarre case where the parse routine
2729 * actually executed more then once (due to a reparse) and ended
2730 * up failing after already having created the File Object.
2731 */
2732 if (OpenPacket->FileObject->FileName.Length)
2733 {
2734 /* It had a name, free it */
2735 ExFreePoolWithTag(OpenPacket->FileObject->FileName.Buffer, TAG_IO_NAME);
2736 }
2737
2738 /* Clear the device object to invalidate the FO, and dereference */
2739 OpenPacket->FileObject->DeviceObject = NULL;
2740 ObDereferenceObject(OpenPacket->FileObject);
2741 }
2742 }
2743 else
2744 {
2745 /* We reached success and have a valid file handle */
2746 OpenPacket->FileObject->Flags |= FO_HANDLE_CREATED;
2747 ASSERT(OpenPacket->FileObject->Type == IO_TYPE_FILE);
2748
2749 /* Enter SEH for write back */
2750 _SEH2_TRY
2751 {
2752 /* Write back the handle and I/O Status */
2753 *FileHandle = LocalHandle;
2754 IoStatusBlock->Information = OpenPacket->Information;
2755 IoStatusBlock->Status = OpenPacket->FinalStatus;
2756
2757 /* Get the Io status */
2758 Status = OpenPacket->FinalStatus;
2759 }
2760 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2761 {
2762 /* Get the exception status */
2763 Status = _SEH2_GetExceptionCode();
2764 }
2765 _SEH2_END;
2766 }
2767
2768 /* Check if we were 100% successful */
2769 if ((OpenPacket->ParseCheck != FALSE) && (OpenPacket->FileObject))
2770 {
2771 /* Dereference the File Object */
2772 ObDereferenceObject(OpenPacket->FileObject);
2773 }
2774
2775 /* Return status */
2776 ExFreePool(OpenPacket);
2777 return Status;
2778 }
2779
2780 /* FUNCTIONS *****************************************************************/
2781
2782 /*
2783 * @unimplemented
2784 */
2785 NTSTATUS
2786 NTAPI
2787 IoCheckQuerySetFileInformation(IN FILE_INFORMATION_CLASS FileInformationClass,
2788 IN ULONG Length,
2789 IN BOOLEAN SetOperation)
2790 {
2791 UNIMPLEMENTED;
2792 return STATUS_NOT_IMPLEMENTED;
2793 }
2794
2795 /*
2796 * @unimplemented
2797 */
2798 NTSTATUS
2799 NTAPI
2800 IoCheckQuotaBufferValidity(IN PFILE_QUOTA_INFORMATION QuotaBuffer,
2801 IN ULONG QuotaLength,
2802 OUT PULONG ErrorOffset)
2803 {
2804 UNIMPLEMENTED;
2805 return STATUS_NOT_IMPLEMENTED;
2806 }
2807
2808 /*
2809 * @implemented
2810 */
2811 NTSTATUS
2812 NTAPI
2813 IoCreateFile(OUT PHANDLE FileHandle,
2814 IN ACCESS_MASK DesiredAccess,
2815 IN POBJECT_ATTRIBUTES ObjectAttributes,
2816 OUT PIO_STATUS_BLOCK IoStatusBlock,
2817 IN PLARGE_INTEGER AllocationSize OPTIONAL,
2818 IN ULONG FileAttributes,
2819 IN ULONG ShareAccess,
2820 IN ULONG Disposition,
2821 IN ULONG CreateOptions,
2822 IN PVOID EaBuffer OPTIONAL,
2823 IN ULONG EaLength,
2824 IN CREATE_FILE_TYPE CreateFileType,
2825 IN PVOID ExtraCreateParameters OPTIONAL,
2826 IN ULONG Options)
2827 {
2828 PAGED_CODE();
2829
2830 return IopCreateFile(FileHandle,
2831 DesiredAccess,
2832 ObjectAttributes,
2833 IoStatusBlock,
2834 AllocationSize,
2835 FileAttributes,
2836 ShareAccess,
2837 Disposition,
2838 CreateOptions,
2839 EaBuffer,
2840 EaLength,
2841 CreateFileType,
2842 ExtraCreateParameters,
2843 Options,
2844 0,
2845 NULL);
2846 }
2847
2848 /*
2849 * @unimplemented
2850 */
2851 NTSTATUS
2852 NTAPI
2853 IoCreateFileSpecifyDeviceObjectHint(OUT PHANDLE FileHandle,
2854 IN ACCESS_MASK DesiredAccess,
2855 IN POBJECT_ATTRIBUTES ObjectAttributes,
2856 OUT PIO_STATUS_BLOCK IoStatusBlock,
2857 IN PLARGE_INTEGER AllocationSize OPTIONAL,
2858 IN ULONG FileAttributes,
2859 IN ULONG ShareAccess,
2860 IN ULONG Disposition,
2861 IN ULONG CreateOptions,
2862 IN PVOID EaBuffer OPTIONAL,
2863 IN ULONG EaLength,
2864 IN CREATE_FILE_TYPE CreateFileType,
2865 IN PVOID ExtraCreateParameters OPTIONAL,
2866 IN ULONG Options,
2867 IN PVOID DeviceObject)
2868 {
2869 ULONG Flags = 0;
2870
2871 PAGED_CODE();
2872
2873 /* Check if we were passed a device to send the create request to*/
2874 if (DeviceObject)
2875 {
2876 /* We'll tag this request into a file object extension */
2877 Flags = (IOP_CREATE_FILE_OBJECT_EXTENSION | IOP_USE_TOP_LEVEL_DEVICE_HINT);
2878 }
2879
2880 return IopCreateFile(FileHandle,
2881 DesiredAccess,
2882 ObjectAttributes,
2883 IoStatusBlock,
2884 AllocationSize,
2885 FileAttributes,
2886 ShareAccess,
2887 Disposition,
2888 CreateOptions,
2889 EaBuffer,
2890 EaLength,
2891 CreateFileType,
2892 ExtraCreateParameters,
2893 Options | IO_NO_PARAMETER_CHECKING,
2894 Flags,
2895 DeviceObject);
2896 }
2897
2898 /*
2899 * @implemented
2900 */
2901 PFILE_OBJECT
2902 NTAPI
2903 IoCreateStreamFileObjectEx(IN PFILE_OBJECT FileObject OPTIONAL,
2904 IN PDEVICE_OBJECT DeviceObject OPTIONAL,
2905 OUT PHANDLE FileObjectHandle OPTIONAL)
2906 {
2907 PFILE_OBJECT CreatedFileObject;
2908 NTSTATUS Status;
2909 HANDLE FileHandle;
2910 OBJECT_ATTRIBUTES ObjectAttributes;
2911 PAGED_CODE();
2912 IOTRACE(IO_FILE_DEBUG, "FileObject: %p\n", FileObject);
2913
2914 /* Choose Device Object */
2915 if (FileObject) DeviceObject = FileObject->DeviceObject;
2916
2917 /* Reference the device object and initialize attributes */
2918 InterlockedIncrement(&DeviceObject->ReferenceCount);
2919 InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
2920
2921 /* Create the File Object */
2922 Status = ObCreateObject(KernelMode,
2923 IoFileObjectType,
2924 &ObjectAttributes,
2925 KernelMode,
2926 NULL,
2927 sizeof(FILE_OBJECT),
2928 sizeof(FILE_OBJECT),
2929 0,
2930 (PVOID*)&CreatedFileObject);
2931 if (!NT_SUCCESS(Status))
2932 {
2933 /* Fail */
2934 IopDereferenceDeviceObject(DeviceObject, FALSE);
2935 ExRaiseStatus(Status);
2936 }
2937
2938 /* Set File Object Data */
2939 RtlZeroMemory(CreatedFileObject, sizeof(FILE_OBJECT));
2940 CreatedFileObject->DeviceObject = DeviceObject;
2941 CreatedFileObject->Type = IO_TYPE_FILE;
2942 CreatedFileObject->Size = sizeof(FILE_OBJECT);
2943 CreatedFileObject->Flags = FO_STREAM_FILE;
2944
2945 /* Initialize the wait event */
2946 KeInitializeEvent(&CreatedFileObject->Event, SynchronizationEvent, FALSE);
2947
2948 /* Insert it to create a handle for it */
2949 Status = ObInsertObject(CreatedFileObject,
2950 NULL,
2951 FILE_READ_DATA,
2952 1,
2953 (PVOID*)&CreatedFileObject,
2954 &FileHandle);
2955 if (!NT_SUCCESS(Status)) ExRaiseStatus(Status);
2956
2957 /* Set the handle created flag */
2958 CreatedFileObject->Flags |= FO_HANDLE_CREATED;
2959 ASSERT(CreatedFileObject->Type == IO_TYPE_FILE);
2960
2961 /* Check if we have a VPB */
2962 if (DeviceObject->Vpb)
2963 {
2964 /* Reference it */
2965 InterlockedIncrement((PLONG)&DeviceObject->Vpb->ReferenceCount);
2966 }
2967
2968 /* Check if the caller wants the handle */
2969 if (FileObjectHandle)
2970 {
2971 /* Return it */
2972 *FileObjectHandle = FileHandle;
2973 ObDereferenceObject(CreatedFileObject);
2974 }
2975 else
2976 {
2977 /* Otherwise, close it */
2978 ObCloseHandle(FileHandle, KernelMode);
2979 }
2980
2981 /* Return the file object */
2982 return CreatedFileObject;
2983 }
2984
2985 /*
2986 * @implemented
2987 */
2988 PFILE_OBJECT
2989 NTAPI
2990 IoCreateStreamFileObject(IN PFILE_OBJECT FileObject,
2991 IN PDEVICE_OBJECT DeviceObject)
2992 {
2993 /* Call the newer function */
2994 return IoCreateStreamFileObjectEx(FileObject, DeviceObject, NULL);
2995 }
2996
2997 /*
2998 * @implemented
2999 */
3000 PFILE_OBJECT
3001 NTAPI
3002 IoCreateStreamFileObjectLite(IN PFILE_OBJECT FileObject OPTIONAL,
3003 IN PDEVICE_OBJECT DeviceObject OPTIONAL)
3004 {
3005 PFILE_OBJECT CreatedFileObject;
3006 NTSTATUS Status;
3007 OBJECT_ATTRIBUTES ObjectAttributes;
3008 PAGED_CODE();
3009 IOTRACE(IO_FILE_DEBUG, "FileObject: %p\n", FileObject);
3010
3011 /* Choose Device Object */
3012 if (FileObject) DeviceObject = FileObject->DeviceObject;
3013
3014 /* Reference the device object and initialize attributes */
3015 InterlockedIncrement(&DeviceObject->ReferenceCount);
3016 InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
3017
3018 /* Create the File Object */
3019 Status = ObCreateObject(KernelMode,
3020 IoFileObjectType,
3021 &ObjectAttributes,
3022 KernelMode,
3023 NULL,
3024 sizeof(FILE_OBJECT),
3025 sizeof(FILE_OBJECT),
3026 0,
3027 (PVOID*)&CreatedFileObject);
3028 if (!NT_SUCCESS(Status))
3029 {
3030 /* Fail */
3031 IopDereferenceDeviceObject(DeviceObject, FALSE);
3032 ExRaiseStatus(Status);
3033 }
3034
3035 /* Set File Object Data */
3036 RtlZeroMemory(CreatedFileObject, sizeof(FILE_OBJECT));
3037 CreatedFileObject->DeviceObject = DeviceObject;
3038 CreatedFileObject->Type = IO_TYPE_FILE;
3039 CreatedFileObject->Size = sizeof(FILE_OBJECT);
3040 CreatedFileObject->Flags = FO_STREAM_FILE;
3041
3042 /* Initialize the wait event */
3043 KeInitializeEvent(&CreatedFileObject->Event, SynchronizationEvent, FALSE);
3044
3045 /* Destroy create information */
3046 ObFreeObjectCreateInfoBuffer(OBJECT_TO_OBJECT_HEADER(CreatedFileObject)->
3047 ObjectCreateInfo);
3048 OBJECT_TO_OBJECT_HEADER(CreatedFileObject)->ObjectCreateInfo = NULL;
3049
3050 /* Set the handle created flag */
3051 CreatedFileObject->Flags |= FO_HANDLE_CREATED;
3052 ASSERT(CreatedFileObject->Type == IO_TYPE_FILE);
3053
3054 /* Check if we have a VPB */
3055 if (DeviceObject->Vpb)
3056 {
3057 /* Reference it */
3058 InterlockedIncrement((PLONG)&DeviceObject->Vpb->ReferenceCount);
3059 }
3060
3061 /* Return the file object */
3062 return CreatedFileObject;
3063 }
3064
3065 /*
3066 * @implemented
3067 */
3068 PGENERIC_MAPPING
3069 NTAPI
3070 IoGetFileObjectGenericMapping(VOID)
3071 {
3072 /* Return the mapping */
3073 return &IopFileMapping;
3074 }
3075
3076 /*
3077 * @implemented
3078 */
3079 BOOLEAN
3080 NTAPI
3081 IoIsFileOriginRemote(IN PFILE_OBJECT FileObject)
3082 {
3083 /* Return the flag status */
3084 return FileObject->Flags & FO_REMOTE_ORIGIN ? TRUE : FALSE;
3085 }
3086
3087 /*
3088 * @implemented
3089 */
3090 BOOLEAN
3091 NTAPI
3092 IoFastQueryNetworkAttributes(IN POBJECT_ATTRIBUTES ObjectAttributes,
3093 IN ACCESS_MASK DesiredAccess,
3094 IN ULONG OpenOptions,
3095 OUT PIO_STATUS_BLOCK IoStatus,
3096 OUT PFILE_NETWORK_OPEN_INFORMATION Buffer)
3097 {
3098 NTSTATUS Status;
3099 DUMMY_FILE_OBJECT LocalFileObject;
3100 HANDLE Handle;
3101 OPEN_PACKET OpenPacket;
3102 PAGED_CODE();
3103 IOTRACE(IO_FILE_DEBUG, "FileName: %wZ\n", ObjectAttributes->ObjectName);
3104
3105 /* Setup the Open Packet */
3106 RtlZeroMemory(&OpenPacket, sizeof(OPEN_PACKET));
3107 OpenPacket.Type = IO_TYPE_OPEN_PACKET;
3108 OpenPacket.Size = sizeof(OPEN_PACKET);
3109 OpenPacket.CreateOptions = OpenOptions | FILE_OPEN_REPARSE_POINT;
3110 OpenPacket.ShareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
3111 OpenPacket.Options = IO_FORCE_ACCESS_CHECK;
3112 OpenPacket.Disposition = FILE_OPEN;
3113 OpenPacket.NetworkInformation = Buffer;
3114 OpenPacket.QueryOnly = TRUE;
3115 OpenPacket.FullAttributes = TRUE;
3116 OpenPacket.LocalFileObject = &LocalFileObject;
3117
3118 /*
3119 * Attempt opening the file. This will call the I/O Parse Routine for
3120 * the File Object (IopParseDevice) which will use the dummy file obejct
3121 * send the IRP to its device object. Note that we have two statuses
3122 * to worry about: the Object Manager's status (in Status) and the I/O
3123 * status, which is in the Open Packet's Final Status, and determined
3124 * by the Parse Check member.
3125 */
3126 Status = ObOpenObjectByName(ObjectAttributes,
3127 NULL,
3128 KernelMode,
3129 NULL,
3130 DesiredAccess,
3131 &OpenPacket,
3132 &Handle);
3133 if (OpenPacket.ParseCheck == FALSE)
3134 {
3135 /* Parse failed */
3136 IoStatus->Status = Status;
3137 }
3138 else
3139 {
3140 /* Use the Io status */
3141 IoStatus->Status = OpenPacket.FinalStatus;
3142 IoStatus->Information = OpenPacket.Information;
3143 }
3144
3145 /* Return success */
3146 return TRUE;
3147 }
3148
3149 /*
3150 * @implemented
3151 */
3152 VOID
3153 NTAPI
3154 IoUpdateShareAccess(IN PFILE_OBJECT FileObject,
3155 OUT PSHARE_ACCESS ShareAccess)
3156 {
3157 PAGED_CODE();
3158
3159 /* Check if the file has an extension */
3160 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3161 {
3162 /* Check if caller specified to ignore access checks */
3163 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3164 {
3165 /* Don't update share access */
3166 return;
3167 }
3168 }
3169
3170 /* Otherwise, check if there's any access present */
3171 if ((FileObject->ReadAccess) ||
3172 (FileObject->WriteAccess) ||
3173 (FileObject->DeleteAccess))
3174 {
3175 /* Increase the open count */
3176 ShareAccess->OpenCount++;
3177
3178 /* Add new share access */
3179 ShareAccess->Readers += FileObject->ReadAccess;
3180 ShareAccess->Writers += FileObject->WriteAccess;
3181 ShareAccess->Deleters += FileObject->DeleteAccess;
3182 ShareAccess->SharedRead += FileObject->SharedRead;
3183 ShareAccess->SharedWrite += FileObject->SharedWrite;
3184 ShareAccess->SharedDelete += FileObject->SharedDelete;
3185 }
3186 }
3187
3188 /*
3189 * @implemented
3190 */
3191 NTSTATUS
3192 NTAPI
3193 IoCheckShareAccess(IN ACCESS_MASK DesiredAccess,
3194 IN ULONG DesiredShareAccess,
3195 IN PFILE_OBJECT FileObject,
3196 IN PSHARE_ACCESS ShareAccess,
3197 IN BOOLEAN Update)
3198 {
3199 BOOLEAN ReadAccess;
3200 BOOLEAN WriteAccess;
3201 BOOLEAN DeleteAccess;
3202 BOOLEAN SharedRead;
3203 BOOLEAN SharedWrite;
3204 BOOLEAN SharedDelete;
3205 PAGED_CODE();
3206
3207 /* Get access masks */
3208 ReadAccess = (DesiredAccess & (FILE_READ_DATA | FILE_EXECUTE)) != 0;
3209 WriteAccess = (DesiredAccess & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0;
3210 DeleteAccess = (DesiredAccess & DELETE) != 0;
3211
3212 /* Set them in the file object */
3213 FileObject->ReadAccess = ReadAccess;
3214 FileObject->WriteAccess = WriteAccess;
3215 FileObject->DeleteAccess = DeleteAccess;
3216
3217 /* Check if the file has an extension */
3218 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3219 {
3220 /* Check if caller specified to ignore access checks */
3221 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3222 {
3223 /* Don't check share access */
3224 return STATUS_SUCCESS;
3225 }
3226 }
3227
3228 /* Check if we have any access */
3229 if ((ReadAccess) || (WriteAccess) || (DeleteAccess))
3230 {
3231 /* Get shared access masks */
3232 SharedRead = (DesiredShareAccess & FILE_SHARE_READ) != 0;
3233 SharedWrite = (DesiredShareAccess & FILE_SHARE_WRITE) != 0;
3234 SharedDelete = (DesiredShareAccess & FILE_SHARE_DELETE) != 0;
3235
3236 /* Set them */
3237 FileObject->SharedRead = SharedRead;
3238 FileObject->SharedWrite = SharedWrite;
3239 FileObject->SharedDelete = SharedDelete;
3240
3241 /* Check if the shared access is violated */
3242 if ((ReadAccess &&
3243 (ShareAccess->SharedRead < ShareAccess->OpenCount)) ||
3244 (WriteAccess &&
3245 (ShareAccess->SharedWrite < ShareAccess->OpenCount)) ||
3246 (DeleteAccess &&
3247 (ShareAccess->SharedDelete < ShareAccess->OpenCount)) ||
3248 ((ShareAccess->Readers != 0) && !SharedRead) ||
3249 ((ShareAccess->Writers != 0) && !SharedWrite) ||
3250 ((ShareAccess->Deleters != 0) && !SharedDelete))
3251 {
3252 /* Sharing violation, fail */
3253 return STATUS_SHARING_VIOLATION;
3254 }
3255
3256 /* It's not, check if caller wants us to update it */
3257 if (Update)
3258 {
3259 /* Increase open count */
3260 ShareAccess->OpenCount++;
3261
3262 /* Update shared access */
3263 ShareAccess->Readers += ReadAccess;
3264 ShareAccess->Writers += WriteAccess;
3265 ShareAccess->Deleters += DeleteAccess;
3266 ShareAccess->SharedRead += SharedRead;
3267 ShareAccess->SharedWrite += SharedWrite;
3268 ShareAccess->SharedDelete += SharedDelete;
3269 }
3270 }
3271
3272 /* Validation successful */
3273 return STATUS_SUCCESS;
3274 }
3275
3276 /*
3277 * @implemented
3278 */
3279 VOID
3280 NTAPI
3281 IoRemoveShareAccess(IN PFILE_OBJECT FileObject,
3282 IN PSHARE_ACCESS ShareAccess)
3283 {
3284 PAGED_CODE();
3285
3286 /* Check if the file has an extension */
3287 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3288 {
3289 /* Check if caller specified to ignore access checks */
3290 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3291 {
3292 /* Don't update share access */
3293 return;
3294 }
3295 }
3296
3297 /* Otherwise, check if there's any access present */
3298 if ((FileObject->ReadAccess) ||
3299 (FileObject->WriteAccess) ||
3300 (FileObject->DeleteAccess))
3301 {
3302 /* Decrement the open count */
3303 ShareAccess->OpenCount--;
3304
3305 /* Remove share access */
3306 ShareAccess->Readers -= FileObject->ReadAccess;
3307 ShareAccess->Writers -= FileObject->WriteAccess;
3308 ShareAccess->Deleters -= FileObject->DeleteAccess;
3309 ShareAccess->SharedRead -= FileObject->SharedRead;
3310 ShareAccess->SharedWrite -= FileObject->SharedWrite;
3311 ShareAccess->SharedDelete -= FileObject->SharedDelete;
3312 }
3313 }
3314
3315 /*
3316 * @implemented
3317 */
3318 VOID
3319 NTAPI
3320 IoSetShareAccess(IN ACCESS_MASK DesiredAccess,
3321 IN ULONG DesiredShareAccess,
3322 IN PFILE_OBJECT FileObject,
3323 OUT PSHARE_ACCESS ShareAccess)
3324 {
3325 BOOLEAN ReadAccess;
3326 BOOLEAN WriteAccess;
3327 BOOLEAN DeleteAccess;
3328 BOOLEAN SharedRead;
3329 BOOLEAN SharedWrite;
3330 BOOLEAN SharedDelete;
3331 BOOLEAN Update = TRUE;
3332 PAGED_CODE();
3333
3334 ReadAccess = (DesiredAccess & (FILE_READ_DATA | FILE_EXECUTE)) != 0;
3335 WriteAccess = (DesiredAccess & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0;
3336 DeleteAccess = (DesiredAccess & DELETE) != 0;
3337
3338 /* Check if the file has an extension */
3339 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3340 {
3341 /* Check if caller specified to ignore access checks */
3342 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3343 {
3344 /* Don't update share access */
3345 Update = FALSE;
3346 }
3347 }
3348
3349 /* Update basic access */
3350 FileObject->ReadAccess = ReadAccess;
3351 FileObject->WriteAccess = WriteAccess;
3352 FileObject->DeleteAccess = DeleteAccess;
3353
3354 /* Check if we have no access as all */
3355 if (!(ReadAccess) && !(WriteAccess) && !(DeleteAccess))
3356 {
3357 /* Check if we need to update the structure */
3358 if (!Update) return;
3359
3360 /* Otherwise, clear data */
3361 ShareAccess->OpenCount = 0;
3362 ShareAccess->Readers = 0;
3363 ShareAccess->Writers = 0;
3364 ShareAccess->Deleters = 0;
3365 ShareAccess->SharedRead = 0;
3366 ShareAccess->SharedWrite = 0;
3367 ShareAccess->SharedDelete = 0;
3368 }
3369 else
3370 {
3371 /* Calculate shared access */
3372 SharedRead = (DesiredShareAccess & FILE_SHARE_READ) != 0;
3373 SharedWrite = (DesiredShareAccess & FILE_SHARE_WRITE) != 0;
3374 SharedDelete = (DesiredShareAccess & FILE_SHARE_DELETE) != 0;
3375
3376 /* Set it in the FO */
3377 FileObject->SharedRead = SharedRead;
3378 FileObject->SharedWrite = SharedWrite;
3379 FileObject->SharedDelete = SharedDelete;
3380
3381 /* Check if we need to update the structure */
3382 if (!Update) return;
3383
3384 /* Otherwise, set data */
3385 ShareAccess->OpenCount = 1;
3386 ShareAccess->Readers = ReadAccess;
3387 ShareAccess->Writers = WriteAccess;
3388 ShareAccess->Deleters = DeleteAccess;
3389 ShareAccess->SharedRead = SharedRead;
3390 ShareAccess->SharedWrite = SharedWrite;
3391 ShareAccess->SharedDelete = SharedDelete;
3392 }
3393 }
3394
3395 /*
3396 * @implemented
3397 */
3398 VOID
3399 NTAPI
3400 IoCancelFileOpen(IN PDEVICE_OBJECT DeviceObject,
3401 IN PFILE_OBJECT FileObject)
3402 {
3403 PIRP Irp;
3404 KEVENT Event;
3405 KIRQL OldIrql;
3406 NTSTATUS Status;
3407 PIO_STACK_LOCATION Stack;
3408
3409 /* Check if handles were already created for the
3410 * open file. If so, that's over.
3411 */
3412 if (FileObject->Flags & FO_HANDLE_CREATED)
3413 KeBugCheckEx(INVALID_CANCEL_OF_FILE_OPEN,
3414 (ULONG_PTR)FileObject,
3415 (ULONG_PTR)DeviceObject, 0, 0);
3416
3417 /* Reset the events */
3418 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
3419 KeClearEvent(&FileObject->Event);
3420
3421 /* Allocate the IRP we'll use */
3422 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
3423 /* Properly set it */
3424 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
3425 Irp->UserEvent = &Event;
3426 Irp->UserIosb = &Irp->IoStatus;
3427 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
3428 Irp->Tail.Overlay.OriginalFileObject = FileObject;
3429 Irp->RequestorMode = KernelMode;
3430 Irp->Flags = IRP_CLOSE_OPERATION | IRP_SYNCHRONOUS_API;
3431
3432 Stack = IoGetNextIrpStackLocation(Irp);
3433 Stack->MajorFunction = IRP_MJ_CLEANUP;
3434 Stack->FileObject = FileObject;
3435
3436 /* Put on top of IRPs list of the thread */
3437 IopQueueIrpToThread(Irp);
3438
3439 /* Call the driver */
3440 Status = IoCallDriver(DeviceObject, Irp);
3441 if (Status == STATUS_PENDING)
3442 {
3443 KeWaitForSingleObject(&Event, UserRequest,
3444 KernelMode, FALSE, NULL);
3445 }
3446
3447 /* Remove from IRPs list */
3448 KeRaiseIrql(APC_LEVEL, &OldIrql);
3449 IopUnQueueIrpFromThread(Irp);
3450 KeLowerIrql(OldIrql);
3451
3452 /* Free the IRP */
3453 IoFreeIrp(Irp);
3454
3455 /* Clear the event */
3456 KeClearEvent(&FileObject->Event);
3457 /* And finally, mark the open operation as canceled */
3458 FileObject->Flags |= FO_FILE_OPEN_CANCELLED;
3459 }
3460
3461 /*
3462 * @unimplemented
3463 */
3464 NTSTATUS
3465 NTAPI