[NTOSKRNL] Rename IopQueryNameFile to IopQueryNameInternal
[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 Status = IoQueryFileInformation(FileObject,
1945 FileNameInformation,
1946 LengthMismatch ? Length : FileLength,
1947 LocalFileInfo,
1948 &LocalReturnLength);
1949 if (NT_ERROR(Status))
1950 {
1951 /* Fail on errors only, allow warnings */
1952 ExFreePoolWithTag(LocalInfo, TAG_IO);
1953 return Status;
1954 }
1955
1956 /* If the provided buffer is too small, return the required size */
1957 if (LengthMismatch)
1958 {
1959 /* Add the required length */
1960 *ReturnLength += LocalFileInfo->FileNameLength;
1961
1962 /* Free the allocated buffer and return failure */
1963 ExFreePoolWithTag(LocalInfo, TAG_IO);
1964 return STATUS_BUFFER_OVERFLOW;
1965 }
1966
1967 /* Now calculate the new lengths left */
1968 FileLength = LocalReturnLength -
1969 FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
1970 LocalReturnLength = (ULONG)((ULONG_PTR)p -
1971 (ULONG_PTR)ObjectNameInfo +
1972 LocalFileInfo->FileNameLength);
1973
1974 /* Write the Name and null-terminate it */
1975 RtlCopyMemory(p, LocalFileInfo->FileName, FileLength);
1976 p += (FileLength / sizeof(WCHAR));
1977 *p = UNICODE_NULL;
1978 LocalReturnLength += sizeof(UNICODE_NULL);
1979
1980 /* Return the length needed */
1981 *ReturnLength = LocalReturnLength;
1982
1983 /* Setup the length and maximum length */
1984 FileLength = (ULONG)((ULONG_PTR)p - (ULONG_PTR)ObjectNameInfo);
1985 ObjectNameInfo->Name.Length = (USHORT)FileLength -
1986 sizeof(OBJECT_NAME_INFORMATION);
1987 ObjectNameInfo->Name.MaximumLength = (USHORT)ObjectNameInfo->Name.Length +
1988 sizeof(UNICODE_NULL);
1989
1990 /* Free buffer and return */
1991 ExFreePoolWithTag(LocalInfo, TAG_IO);
1992 return Status;
1993 }
1994
1995 VOID
1996 NTAPI
1997 IopCloseFile(IN PEPROCESS Process OPTIONAL,
1998 IN PVOID ObjectBody,
1999 IN ACCESS_MASK GrantedAccess,
2000 IN ULONG HandleCount,
2001 IN ULONG SystemHandleCount)
2002 {
2003 PFILE_OBJECT FileObject = (PFILE_OBJECT)ObjectBody;
2004 KEVENT Event;
2005 PIRP Irp;
2006 PIO_STACK_LOCATION StackPtr;
2007 NTSTATUS Status;
2008 PDEVICE_OBJECT DeviceObject;
2009 KIRQL OldIrql;
2010 IO_STATUS_BLOCK IoStatusBlock;
2011 IOTRACE(IO_FILE_DEBUG, "ObjectBody: %p\n", ObjectBody);
2012
2013 /* If this isn't the last handle for the current process, quit */
2014 if (HandleCount != 1) return;
2015
2016 /* Check if the file is locked and has more then one handle opened */
2017 if ((FileObject->LockOperation) && (SystemHandleCount != 1))
2018 {
2019 /* Check if this is a direct open or not */
2020 if (BooleanFlagOn(FileObject->Flags, FO_DIRECT_DEVICE_OPEN))
2021 {
2022 /* Get the attached device */
2023 DeviceObject = IoGetAttachedDevice(FileObject->DeviceObject);
2024 }
2025 else
2026 {
2027 /* Get the FO's device */
2028 DeviceObject = IoGetRelatedDeviceObject(FileObject);
2029 }
2030
2031 /* Check if this is a sync FO and lock it */
2032 if (BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2033 {
2034 (VOID)IopLockFileObject(FileObject, KernelMode);
2035 }
2036
2037 /* Go the FastIO path if possible, otherwise fall back to IRP */
2038 if (DeviceObject->DriverObject->FastIoDispatch == NULL ||
2039 DeviceObject->DriverObject->FastIoDispatch->FastIoUnlockAll == NULL ||
2040 !DeviceObject->DriverObject->FastIoDispatch->FastIoUnlockAll(FileObject, PsGetCurrentProcess(), &IoStatusBlock, DeviceObject))
2041 {
2042 /* Clear and set up Events */
2043 KeClearEvent(&FileObject->Event);
2044 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
2045
2046 /* Allocate an IRP */
2047 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
2048
2049 /* Set it up */
2050 Irp->UserEvent = &Event;
2051 Irp->UserIosb = &Irp->IoStatus;
2052 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
2053 Irp->Tail.Overlay.OriginalFileObject = FileObject;
2054 Irp->RequestorMode = KernelMode;
2055 Irp->Flags = IRP_SYNCHRONOUS_API;
2056 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
2057 ObReferenceObject(FileObject);
2058
2059 /* Set up Stack Pointer Data */
2060 StackPtr = IoGetNextIrpStackLocation(Irp);
2061 StackPtr->MajorFunction = IRP_MJ_LOCK_CONTROL;
2062 StackPtr->MinorFunction = IRP_MN_UNLOCK_ALL;
2063 StackPtr->FileObject = FileObject;
2064
2065 /* Queue the IRP */
2066 IopQueueIrpToThread(Irp);
2067
2068 /* Call the FS Driver */
2069 Status = IoCallDriver(DeviceObject, Irp);
2070 if (Status == STATUS_PENDING)
2071 {
2072 /* Wait for completion */
2073 KeWaitForSingleObject(&Event, UserRequest, KernelMode, FALSE, NULL);
2074 }
2075
2076 /* IO will unqueue & free for us */
2077 }
2078
2079 /* Release the lock if we were holding it */
2080 if (BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2081 {
2082 IopUnlockFileObject(FileObject);
2083 }
2084 }
2085
2086 /* Make sure this is the last handle */
2087 if (SystemHandleCount != 1) return;
2088
2089 /* Check if this is a direct open or not */
2090 if (FileObject->Flags & FO_DIRECT_DEVICE_OPEN)
2091 {
2092 /* Get the attached device */
2093 DeviceObject = IoGetAttachedDevice(FileObject->DeviceObject);
2094 }
2095 else
2096 {
2097 /* Get the FO's device */
2098 DeviceObject = IoGetRelatedDeviceObject(FileObject);
2099 }
2100
2101 /* Set the handle created flag */
2102 FileObject->Flags |= FO_HANDLE_CREATED;
2103
2104 /* Check if this is a sync FO and lock it */
2105 if (Process != NULL &&
2106 BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2107 {
2108 (VOID)IopLockFileObject(FileObject, KernelMode);
2109 }
2110
2111 /* Clear and set up Events */
2112 KeClearEvent(&FileObject->Event);
2113 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
2114
2115 /* Allocate an IRP */
2116 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
2117
2118 /* Set it up */
2119 Irp->UserEvent = &Event;
2120 Irp->UserIosb = &Irp->IoStatus;
2121 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
2122 Irp->Tail.Overlay.OriginalFileObject = FileObject;
2123 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
2124 Irp->Flags = IRP_CLOSE_OPERATION | IRP_SYNCHRONOUS_API;
2125
2126 /* Set up Stack Pointer Data */
2127 StackPtr = IoGetNextIrpStackLocation(Irp);
2128 StackPtr->MajorFunction = IRP_MJ_CLEANUP;
2129 StackPtr->FileObject = FileObject;
2130
2131 /* Queue the IRP */
2132 IopQueueIrpToThread(Irp);
2133
2134 /* Update operation counts */
2135 IopUpdateOperationCount(IopOtherTransfer);
2136
2137 /* Call the FS Driver */
2138 Status = IoCallDriver(DeviceObject, Irp);
2139 if (Status == STATUS_PENDING)
2140 {
2141 /* Wait for completion */
2142 KeWaitForSingleObject(&Event, UserRequest, KernelMode, FALSE, NULL);
2143 }
2144
2145 /* Unqueue the IRP */
2146 KeRaiseIrql(APC_LEVEL, &OldIrql);
2147 IopUnQueueIrpFromThread(Irp);
2148 KeLowerIrql(OldIrql);
2149
2150 /* Free the IRP */
2151 IoFreeIrp(Irp);
2152
2153 /* Release the lock if we were holding it */
2154 if (Process != NULL &&
2155 BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO))
2156 {
2157 IopUnlockFileObject(FileObject);
2158 }
2159 }
2160
2161 NTSTATUS
2162 NTAPI
2163 IopQueryAttributesFile(IN POBJECT_ATTRIBUTES ObjectAttributes,
2164 IN FILE_INFORMATION_CLASS FileInformationClass,
2165 IN ULONG FileInformationSize,
2166 OUT PVOID FileInformation)
2167 {
2168 NTSTATUS Status;
2169 KPROCESSOR_MODE AccessMode = ExGetPreviousMode();
2170 DUMMY_FILE_OBJECT LocalFileObject;
2171 FILE_NETWORK_OPEN_INFORMATION NetworkOpenInfo;
2172 HANDLE Handle;
2173 OPEN_PACKET OpenPacket;
2174 BOOLEAN IsBasic;
2175 PAGED_CODE();
2176 IOTRACE(IO_FILE_DEBUG, "Class: %lx\n", FileInformationClass);
2177
2178 /* Check if the caller was user mode */
2179 if (AccessMode != KernelMode)
2180 {
2181 /* Protect probe in SEH */
2182 _SEH2_TRY
2183 {
2184 /* Probe the buffer */
2185 ProbeForWrite(FileInformation, FileInformationSize, sizeof(ULONG));
2186 }
2187 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2188 {
2189 /* Return the exception code */
2190 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2191 }
2192 _SEH2_END;
2193 }
2194
2195 /* Check if this is a basic or full request */
2196 IsBasic = (FileInformationSize == sizeof(FILE_BASIC_INFORMATION));
2197
2198 /* Setup the Open Packet */
2199 RtlZeroMemory(&OpenPacket, sizeof(OPEN_PACKET));
2200 OpenPacket.Type = IO_TYPE_OPEN_PACKET;
2201 OpenPacket.Size = sizeof(OPEN_PACKET);
2202 OpenPacket.CreateOptions = FILE_OPEN_REPARSE_POINT;
2203 OpenPacket.ShareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
2204 OpenPacket.Disposition = FILE_OPEN;
2205 OpenPacket.BasicInformation = IsBasic ? FileInformation : NULL;
2206 OpenPacket.NetworkInformation = IsBasic ? &NetworkOpenInfo :
2207 (AccessMode != KernelMode) ?
2208 &NetworkOpenInfo : FileInformation;
2209 OpenPacket.QueryOnly = TRUE;
2210 OpenPacket.FullAttributes = IsBasic ? FALSE : TRUE;
2211 OpenPacket.LocalFileObject = &LocalFileObject;
2212
2213 /* Update the operation count */
2214 IopUpdateOperationCount(IopOtherTransfer);
2215
2216 /*
2217 * Attempt opening the file. This will call the I/O Parse Routine for
2218 * the File Object (IopParseDevice) which will use the dummy file obejct
2219 * send the IRP to its device object. Note that we have two statuses
2220 * to worry about: the Object Manager's status (in Status) and the I/O
2221 * status, which is in the Open Packet's Final Status, and determined
2222 * by the Parse Check member.
2223 */
2224 Status = ObOpenObjectByName(ObjectAttributes,
2225 NULL,
2226 AccessMode,
2227 NULL,
2228 FILE_READ_ATTRIBUTES,
2229 &OpenPacket,
2230 &Handle);
2231 if (OpenPacket.ParseCheck == FALSE)
2232 {
2233 /* Parse failed */
2234 DPRINT("IopQueryAttributesFile failed for '%wZ' with 0x%lx\n",
2235 ObjectAttributes->ObjectName, Status);
2236 return Status;
2237 }
2238 else
2239 {
2240 /* Use the Io status */
2241 Status = OpenPacket.FinalStatus;
2242 }
2243
2244 /* Check if we were succesful and this was user mode and a full query */
2245 if ((NT_SUCCESS(Status)) && (AccessMode != KernelMode) && !(IsBasic))
2246 {
2247 /* Enter SEH for copy */
2248 _SEH2_TRY
2249 {
2250 /* Copy the buffer back */
2251 RtlCopyMemory(FileInformation,
2252 &NetworkOpenInfo,
2253 FileInformationSize);
2254 }
2255 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2256 {
2257 /* Get exception code */
2258 Status = _SEH2_GetExceptionCode();
2259 }
2260 _SEH2_END;
2261 }
2262
2263 /* Return status */
2264 return Status;
2265 }
2266
2267 NTSTATUS
2268 NTAPI
2269 IopAcquireFileObjectLock(
2270 _In_ PFILE_OBJECT FileObject,
2271 _In_ KPROCESSOR_MODE WaitMode,
2272 _In_ BOOLEAN Alertable,
2273 _Out_ PBOOLEAN LockFailed)
2274 {
2275 NTSTATUS Status;
2276
2277 PAGED_CODE();
2278
2279 InterlockedIncrement((PLONG)&FileObject->Waiters);
2280
2281 Status = STATUS_SUCCESS;
2282 do
2283 {
2284 if (!InterlockedExchange((PLONG)&FileObject->Busy, TRUE))
2285 {
2286 break;
2287 }
2288 Status = KeWaitForSingleObject(&FileObject->Lock,
2289 Executive,
2290 WaitMode,
2291 Alertable,
2292 NULL);
2293 } while (Status == STATUS_SUCCESS);
2294
2295 InterlockedDecrement((PLONG)&FileObject->Waiters);
2296 if (Status == STATUS_SUCCESS)
2297 {
2298 ObReferenceObject(FileObject);
2299 *LockFailed = FALSE;
2300 }
2301 else
2302 {
2303 if (!FileObject->Busy && FileObject->Waiters)
2304 {
2305 KeSetEvent(&FileObject->Lock, IO_NO_INCREMENT, FALSE);
2306 }
2307 *LockFailed = TRUE;
2308 }
2309
2310 return Status;
2311 }
2312
2313 PVOID
2314 NTAPI
2315 IoGetFileObjectFilterContext(IN PFILE_OBJECT FileObject)
2316 {
2317 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
2318 {
2319 UNIMPLEMENTED;
2320 /* FIXME: return NULL for the moment ~ */
2321 return NULL;
2322 }
2323
2324 return NULL;
2325 }
2326
2327 NTSTATUS
2328 NTAPI
2329 IoChangeFileObjectFilterContext(IN PFILE_OBJECT FileObject,
2330 IN PVOID FilterContext,
2331 IN BOOLEAN Define)
2332 {
2333 if (!(FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION))
2334 {
2335 return STATUS_INVALID_PARAMETER;
2336 }
2337
2338 UNIMPLEMENTED;
2339
2340 return STATUS_NOT_IMPLEMENTED;
2341 }
2342
2343 NTSTATUS
2344 NTAPI
2345 IopCreateFile(OUT PHANDLE FileHandle,
2346 IN ACCESS_MASK DesiredAccess,
2347 IN POBJECT_ATTRIBUTES ObjectAttributes,
2348 OUT PIO_STATUS_BLOCK IoStatusBlock,
2349 IN PLARGE_INTEGER AllocationSize OPTIONAL,
2350 IN ULONG FileAttributes,
2351 IN ULONG ShareAccess,
2352 IN ULONG Disposition,
2353 IN ULONG CreateOptions,
2354 IN PVOID EaBuffer OPTIONAL,
2355 IN ULONG EaLength,
2356 IN CREATE_FILE_TYPE CreateFileType,
2357 IN PVOID ExtraCreateParameters OPTIONAL,
2358 IN ULONG Options,
2359 IN ULONG Flags,
2360 IN PDEVICE_OBJECT DeviceObject OPTIONAL)
2361 {
2362 KPROCESSOR_MODE AccessMode;
2363 HANDLE LocalHandle = 0;
2364 LARGE_INTEGER SafeAllocationSize;
2365 NTSTATUS Status = STATUS_SUCCESS;
2366 PNAMED_PIPE_CREATE_PARAMETERS NamedPipeCreateParameters;
2367 POPEN_PACKET OpenPacket;
2368 ULONG EaErrorOffset;
2369 PAGED_CODE();
2370
2371 IOTRACE(IO_FILE_DEBUG, "FileName: %wZ\n", ObjectAttributes->ObjectName);
2372
2373
2374 /* Check if we have no parameter checking to do */
2375 if (Options & IO_NO_PARAMETER_CHECKING)
2376 {
2377 /* Then force kernel-mode access to avoid checks */
2378 AccessMode = KernelMode;
2379 }
2380 else
2381 {
2382 /* Otherwise, use the actual mode */
2383 AccessMode = ExGetPreviousMode();
2384 }
2385
2386 /* Check if we need to do parameter checking */
2387 if ((AccessMode != KernelMode) || (Options & IO_CHECK_CREATE_PARAMETERS))
2388 {
2389 /* Validate parameters */
2390 if (FileAttributes & ~FILE_ATTRIBUTE_VALID_FLAGS)
2391 {
2392 DPRINT1("File Create 'FileAttributes' Parameter contains invalid flags!\n");
2393 return STATUS_INVALID_PARAMETER;
2394 }
2395
2396 if (ShareAccess & ~FILE_SHARE_VALID_FLAGS)
2397 {
2398 DPRINT1("File Create 'ShareAccess' Parameter contains invalid flags!\n");
2399 return STATUS_INVALID_PARAMETER;
2400 }
2401
2402 if (Disposition > FILE_MAXIMUM_DISPOSITION)
2403 {
2404 DPRINT1("File Create 'Disposition' Parameter is out of range!\n");
2405 return STATUS_INVALID_PARAMETER;
2406 }
2407
2408 if (CreateOptions & ~FILE_VALID_OPTION_FLAGS)
2409 {
2410 DPRINT1("File Create 'CreateOptions' parameter contains invalid flags!\n");
2411 return STATUS_INVALID_PARAMETER;
2412 }
2413
2414 if ((CreateOptions & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) &&
2415 (!(DesiredAccess & SYNCHRONIZE)))
2416 {
2417 DPRINT1("File Create 'CreateOptions' parameter FILE_SYNCHRONOUS_IO_* requested, but 'DesiredAccess' does not have SYNCHRONIZE!\n");
2418 return STATUS_INVALID_PARAMETER;
2419 }
2420
2421 if ((CreateOptions & FILE_DELETE_ON_CLOSE) && (!(DesiredAccess & DELETE)))
2422 {
2423 DPRINT1("File Create 'CreateOptions' parameter FILE_DELETE_ON_CLOSE requested, but 'DesiredAccess' does not have DELETE!\n");
2424 return STATUS_INVALID_PARAMETER;
2425 }
2426
2427 if ((CreateOptions & (FILE_SYNCHRONOUS_IO_NONALERT | FILE_SYNCHRONOUS_IO_ALERT)) ==
2428 (FILE_SYNCHRONOUS_IO_NONALERT | FILE_SYNCHRONOUS_IO_ALERT))
2429 {
2430 DPRINT1("File Create 'FileAttributes' parameter both FILE_SYNCHRONOUS_IO_NONALERT and FILE_SYNCHRONOUS_IO_ALERT specified!\n");
2431 return STATUS_INVALID_PARAMETER;
2432 }
2433
2434 if ((CreateOptions & FILE_DIRECTORY_FILE) && !(CreateOptions & FILE_NON_DIRECTORY_FILE) &&
2435 (CreateOptions & ~(FILE_DIRECTORY_FILE |
2436 FILE_SYNCHRONOUS_IO_ALERT |
2437 FILE_SYNCHRONOUS_IO_NONALERT |
2438 FILE_WRITE_THROUGH |
2439 FILE_COMPLETE_IF_OPLOCKED |
2440 FILE_OPEN_FOR_BACKUP_INTENT |
2441 FILE_DELETE_ON_CLOSE |
2442 FILE_OPEN_FOR_FREE_SPACE_QUERY |
2443 FILE_OPEN_BY_FILE_ID |
2444 FILE_NO_COMPRESSION |
2445 FILE_OPEN_REPARSE_POINT)))
2446 {
2447 DPRINT1("File Create 'CreateOptions' Parameter has flags incompatible with FILE_DIRECTORY_FILE!\n");
2448 return STATUS_INVALID_PARAMETER;
2449 }
2450
2451 if ((CreateOptions & FILE_DIRECTORY_FILE) && !(CreateOptions & FILE_NON_DIRECTORY_FILE) &&
2452 (Disposition != FILE_CREATE) && (Disposition != FILE_OPEN) && (Disposition != FILE_OPEN_IF))
2453 {
2454 DPRINT1("File Create 'CreateOptions' Parameter FILE_DIRECTORY_FILE requested, but 'Disposition' is not FILE_CREATE/FILE_OPEN/FILE_OPEN_IF!\n");
2455 return STATUS_INVALID_PARAMETER;
2456 }
2457
2458 if ((CreateOptions & FILE_COMPLETE_IF_OPLOCKED) && (CreateOptions & FILE_RESERVE_OPFILTER))
2459 {
2460 DPRINT1("File Create 'CreateOptions' Parameter both FILE_COMPLETE_IF_OPLOCKED and FILE_RESERVE_OPFILTER specified!\n");
2461 return STATUS_INVALID_PARAMETER;
2462 }
2463
2464 if ((CreateOptions & FILE_NO_INTERMEDIATE_BUFFERING) && (DesiredAccess & FILE_APPEND_DATA))
2465 {
2466 DPRINT1("File Create 'CreateOptions' parameter FILE_NO_INTERMEDIATE_BUFFERING requested, but 'DesiredAccess' FILE_APPEND_DATA requires it!\n");
2467 return STATUS_INVALID_PARAMETER;
2468 }
2469
2470 /* Now check if this is a named pipe */
2471 if (CreateFileType == CreateFileTypeNamedPipe)
2472 {
2473 /* Make sure we have extra parameters */
2474 if (!ExtraCreateParameters)
2475 {
2476 DPRINT1("Invalid parameter: ExtraCreateParameters == 0!\n");
2477 return STATUS_INVALID_PARAMETER;
2478 }
2479
2480 /* Get the parameters and validate them */
2481 NamedPipeCreateParameters = ExtraCreateParameters;
2482 if ((NamedPipeCreateParameters->NamedPipeType > FILE_PIPE_MESSAGE_TYPE) ||
2483 (NamedPipeCreateParameters->ReadMode > FILE_PIPE_MESSAGE_MODE) ||
2484 (NamedPipeCreateParameters->CompletionMode > FILE_PIPE_COMPLETE_OPERATION) ||
2485 (ShareAccess & FILE_SHARE_DELETE) ||
2486 ((Disposition < FILE_OPEN) || (Disposition > FILE_OPEN_IF)) ||
2487 (CreateOptions & ~FILE_VALID_PIPE_OPTION_FLAGS))
2488 {
2489 /* Invalid named pipe create */
2490 DPRINT1("Invalid named pipe create\n");
2491 return STATUS_INVALID_PARAMETER;
2492 }
2493 }
2494 else if (CreateFileType == CreateFileTypeMailslot)
2495 {
2496 /* Make sure we have extra parameters */
2497 if (!ExtraCreateParameters)
2498 {
2499 DPRINT1("Invalid parameter: ExtraCreateParameters == 0!\n");
2500 return STATUS_INVALID_PARAMETER;
2501 }
2502
2503 /* Get the parameters and validate them */
2504 if ((ShareAccess & FILE_SHARE_DELETE) ||
2505 !(ShareAccess & ~FILE_SHARE_WRITE) ||
2506 (Disposition != FILE_CREATE) ||
2507 (CreateOptions & ~FILE_VALID_MAILSLOT_OPTION_FLAGS))
2508 {
2509 /* Invalid mailslot create */
2510 DPRINT1("Invalid mailslot create\n");
2511 return STATUS_INVALID_PARAMETER;
2512 }
2513 }
2514 }
2515
2516 /* Allocate the open packet */
2517 OpenPacket = ExAllocatePoolWithTag(NonPagedPool, sizeof(*OpenPacket), 'pOoI');
2518 if (!OpenPacket) return STATUS_INSUFFICIENT_RESOURCES;
2519 RtlZeroMemory(OpenPacket, sizeof(*OpenPacket));
2520
2521 /* Check if the call came from user mode */
2522 if (AccessMode != KernelMode)
2523 {
2524 _SEH2_TRY
2525 {
2526 /* Probe the output parameters */
2527 ProbeForWriteHandle(FileHandle);
2528 ProbeForWriteIoStatusBlock(IoStatusBlock);
2529
2530 /* Probe the allocation size if one was passed in */
2531 if (AllocationSize)
2532 {
2533 SafeAllocationSize = ProbeForReadLargeInteger(AllocationSize);
2534 }
2535 else
2536 {
2537 SafeAllocationSize.QuadPart = 0;
2538 }
2539
2540 /* Make sure it's valid */
2541 if (SafeAllocationSize.QuadPart < 0)
2542 {
2543 RtlRaiseStatus(STATUS_INVALID_PARAMETER);
2544 }
2545
2546 /* Check if EA was passed in */
2547 if ((EaBuffer) && (EaLength))
2548 {
2549 /* Probe it */
2550 ProbeForRead(EaBuffer, EaLength, sizeof(ULONG));
2551
2552 /* And marshall it */
2553 OpenPacket->EaBuffer = ExAllocatePoolWithTag(NonPagedPool,
2554 EaLength,
2555 TAG_EA);
2556 OpenPacket->EaLength = EaLength;
2557 RtlCopyMemory(OpenPacket->EaBuffer, EaBuffer, EaLength);
2558
2559 /* Validate the buffer */
2560 Status = IoCheckEaBufferValidity(OpenPacket->EaBuffer,
2561 EaLength,
2562 &EaErrorOffset);
2563 if (!NT_SUCCESS(Status))
2564 {
2565 /* Undo everything if it's invalid */
2566 DPRINT1("Invalid EA buffer\n");
2567 IoStatusBlock->Status = Status;
2568 IoStatusBlock->Information = EaErrorOffset;
2569 RtlRaiseStatus(Status);
2570 }
2571 }
2572 }
2573 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2574 {
2575 /* Return the exception code */
2576 if (OpenPacket->EaBuffer != NULL) ExFreePool(OpenPacket->EaBuffer);
2577 ExFreePool(OpenPacket);
2578 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2579 }
2580 _SEH2_END;
2581 }
2582 else
2583 {
2584 /* Check if this is a device attach */
2585 if (CreateOptions & IO_ATTACH_DEVICE_API)
2586 {
2587 /* Set the flag properly */
2588 Options |= IO_ATTACH_DEVICE;
2589 CreateOptions &= ~IO_ATTACH_DEVICE_API;
2590 }
2591
2592 /* Check if we have allocation size */
2593 if (AllocationSize)
2594 {
2595 /* Capture it */
2596 SafeAllocationSize = *AllocationSize;
2597 }
2598 else
2599 {
2600 /* Otherwise, no size */
2601 SafeAllocationSize.QuadPart = 0;
2602 }
2603
2604 /* Check if we have an EA packet */
2605 if ((EaBuffer) && (EaLength))
2606 {
2607 /* Allocate the kernel copy */
2608 OpenPacket->EaBuffer = ExAllocatePoolWithTag(NonPagedPool,
2609 EaLength,
2610 TAG_EA);
2611 if (!OpenPacket->EaBuffer)
2612 {
2613 ExFreePool(OpenPacket);
2614 DPRINT1("Failed to allocate open packet EA buffer\n");
2615 return STATUS_INSUFFICIENT_RESOURCES;
2616 }
2617
2618 /* Copy the data */
2619 OpenPacket->EaLength = EaLength;
2620 RtlCopyMemory(OpenPacket->EaBuffer, EaBuffer, EaLength);
2621
2622 /* Validate the buffer */
2623 Status = IoCheckEaBufferValidity(OpenPacket->EaBuffer,
2624 EaLength,
2625 &EaErrorOffset);
2626 if (!NT_SUCCESS(Status))
2627 {
2628 /* Undo everything if it's invalid */
2629 DPRINT1("Invalid EA buffer\n");
2630 ExFreePool(OpenPacket->EaBuffer);
2631 IoStatusBlock->Status = Status;
2632 IoStatusBlock->Information = EaErrorOffset;
2633 ExFreePool(OpenPacket);
2634 return Status;
2635 }
2636 }
2637 }
2638
2639 /* Setup the Open Packet */
2640 OpenPacket->Type = IO_TYPE_OPEN_PACKET;
2641 OpenPacket->Size = sizeof(*OpenPacket);
2642 OpenPacket->AllocationSize = SafeAllocationSize;
2643 OpenPacket->CreateOptions = CreateOptions;
2644 OpenPacket->FileAttributes = (USHORT)FileAttributes;
2645 OpenPacket->ShareAccess = (USHORT)ShareAccess;
2646 OpenPacket->Options = Options;
2647 OpenPacket->Disposition = Disposition;
2648 OpenPacket->CreateFileType = CreateFileType;
2649 OpenPacket->ExtraCreateParameters = ExtraCreateParameters;
2650 OpenPacket->InternalFlags = Flags;
2651 OpenPacket->TopDeviceObjectHint = DeviceObject;
2652
2653 /* Update the operation count */
2654 IopUpdateOperationCount(IopOtherTransfer);
2655
2656 /*
2657 * Attempt opening the file. This will call the I/O Parse Routine for
2658 * the File Object (IopParseDevice) which will create the object and
2659 * send the IRP to its device object. Note that we have two statuses
2660 * to worry about: the Object Manager's status (in Status) and the I/O
2661 * status, which is in the Open Packet's Final Status, and determined
2662 * by the Parse Check member.
2663 */
2664 Status = ObOpenObjectByName(ObjectAttributes,
2665 NULL,
2666 AccessMode,
2667 NULL,
2668 DesiredAccess,
2669 OpenPacket,
2670 &LocalHandle);
2671
2672 /* Free the EA Buffer */
2673 if (OpenPacket->EaBuffer) ExFreePool(OpenPacket->EaBuffer);
2674
2675 /* Now check for Ob or Io failure */
2676 if (!(NT_SUCCESS(Status)) || (OpenPacket->ParseCheck == FALSE))
2677 {
2678 /* Check if Ob thinks well went well */
2679 if (NT_SUCCESS(Status))
2680 {
2681 /*
2682 * Tell it otherwise. Because we didn't use an ObjectType,
2683 * it incorrectly returned us a handle to God knows what.
2684 */
2685 ZwClose(LocalHandle);
2686 Status = STATUS_OBJECT_TYPE_MISMATCH;
2687 }
2688
2689 /* Now check the Io status */
2690 if (!NT_SUCCESS(OpenPacket->FinalStatus))
2691 {
2692 /* Use this status instead of Ob's */
2693 Status = OpenPacket->FinalStatus;
2694
2695 /* Check if it was only a warning */
2696 if (NT_WARNING(Status))
2697 {
2698 /* Protect write with SEH */
2699 _SEH2_TRY
2700 {
2701 /* In this case, we copy the I/O Status back */
2702 IoStatusBlock->Information = OpenPacket->Information;
2703 IoStatusBlock->Status = OpenPacket->FinalStatus;
2704 }
2705 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2706 {
2707 /* Get exception code */
2708 Status = _SEH2_GetExceptionCode();
2709 }
2710 _SEH2_END;
2711 }
2712 }
2713 else if ((OpenPacket->FileObject) && (OpenPacket->ParseCheck == FALSE))
2714 {
2715 /*
2716 * This can happen in the very bizarre case where the parse routine
2717 * actually executed more then once (due to a reparse) and ended
2718 * up failing after already having created the File Object.
2719 */
2720 if (OpenPacket->FileObject->FileName.Length)
2721 {
2722 /* It had a name, free it */
2723 ExFreePoolWithTag(OpenPacket->FileObject->FileName.Buffer, TAG_IO_NAME);
2724 }
2725
2726 /* Clear the device object to invalidate the FO, and dereference */
2727 OpenPacket->FileObject->DeviceObject = NULL;
2728 ObDereferenceObject(OpenPacket->FileObject);
2729 }
2730 }
2731 else
2732 {
2733 /* We reached success and have a valid file handle */
2734 OpenPacket->FileObject->Flags |= FO_HANDLE_CREATED;
2735 ASSERT(OpenPacket->FileObject->Type == IO_TYPE_FILE);
2736
2737 /* Enter SEH for write back */
2738 _SEH2_TRY
2739 {
2740 /* Write back the handle and I/O Status */
2741 *FileHandle = LocalHandle;
2742 IoStatusBlock->Information = OpenPacket->Information;
2743 IoStatusBlock->Status = OpenPacket->FinalStatus;
2744
2745 /* Get the Io status */
2746 Status = OpenPacket->FinalStatus;
2747 }
2748 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2749 {
2750 /* Get the exception status */
2751 Status = _SEH2_GetExceptionCode();
2752 }
2753 _SEH2_END;
2754 }
2755
2756 /* Check if we were 100% successful */
2757 if ((OpenPacket->ParseCheck != FALSE) && (OpenPacket->FileObject))
2758 {
2759 /* Dereference the File Object */
2760 ObDereferenceObject(OpenPacket->FileObject);
2761 }
2762
2763 /* Return status */
2764 ExFreePool(OpenPacket);
2765 return Status;
2766 }
2767
2768 /* FUNCTIONS *****************************************************************/
2769
2770 /*
2771 * @unimplemented
2772 */
2773 NTSTATUS
2774 NTAPI
2775 IoCheckQuerySetFileInformation(IN FILE_INFORMATION_CLASS FileInformationClass,
2776 IN ULONG Length,
2777 IN BOOLEAN SetOperation)
2778 {
2779 UNIMPLEMENTED;
2780 return STATUS_NOT_IMPLEMENTED;
2781 }
2782
2783 /*
2784 * @unimplemented
2785 */
2786 NTSTATUS
2787 NTAPI
2788 IoCheckQuotaBufferValidity(IN PFILE_QUOTA_INFORMATION QuotaBuffer,
2789 IN ULONG QuotaLength,
2790 OUT PULONG ErrorOffset)
2791 {
2792 UNIMPLEMENTED;
2793 return STATUS_NOT_IMPLEMENTED;
2794 }
2795
2796 /*
2797 * @implemented
2798 */
2799 NTSTATUS
2800 NTAPI
2801 IoCreateFile(OUT PHANDLE FileHandle,
2802 IN ACCESS_MASK DesiredAccess,
2803 IN POBJECT_ATTRIBUTES ObjectAttributes,
2804 OUT PIO_STATUS_BLOCK IoStatusBlock,
2805 IN PLARGE_INTEGER AllocationSize OPTIONAL,
2806 IN ULONG FileAttributes,
2807 IN ULONG ShareAccess,
2808 IN ULONG Disposition,
2809 IN ULONG CreateOptions,
2810 IN PVOID EaBuffer OPTIONAL,
2811 IN ULONG EaLength,
2812 IN CREATE_FILE_TYPE CreateFileType,
2813 IN PVOID ExtraCreateParameters OPTIONAL,
2814 IN ULONG Options)
2815 {
2816 PAGED_CODE();
2817
2818 return IopCreateFile(FileHandle,
2819 DesiredAccess,
2820 ObjectAttributes,
2821 IoStatusBlock,
2822 AllocationSize,
2823 FileAttributes,
2824 ShareAccess,
2825 Disposition,
2826 CreateOptions,
2827 EaBuffer,
2828 EaLength,
2829 CreateFileType,
2830 ExtraCreateParameters,
2831 Options,
2832 0,
2833 NULL);
2834 }
2835
2836 /*
2837 * @unimplemented
2838 */
2839 NTSTATUS
2840 NTAPI
2841 IoCreateFileSpecifyDeviceObjectHint(OUT PHANDLE FileHandle,
2842 IN ACCESS_MASK DesiredAccess,
2843 IN POBJECT_ATTRIBUTES ObjectAttributes,
2844 OUT PIO_STATUS_BLOCK IoStatusBlock,
2845 IN PLARGE_INTEGER AllocationSize OPTIONAL,
2846 IN ULONG FileAttributes,
2847 IN ULONG ShareAccess,
2848 IN ULONG Disposition,
2849 IN ULONG CreateOptions,
2850 IN PVOID EaBuffer OPTIONAL,
2851 IN ULONG EaLength,
2852 IN CREATE_FILE_TYPE CreateFileType,
2853 IN PVOID ExtraCreateParameters OPTIONAL,
2854 IN ULONG Options,
2855 IN PVOID DeviceObject)
2856 {
2857 ULONG Flags = 0;
2858
2859 PAGED_CODE();
2860
2861 /* Check if we were passed a device to send the create request to*/
2862 if (DeviceObject)
2863 {
2864 /* We'll tag this request into a file object extension */
2865 Flags = (IOP_CREATE_FILE_OBJECT_EXTENSION | IOP_USE_TOP_LEVEL_DEVICE_HINT);
2866 }
2867
2868 return IopCreateFile(FileHandle,
2869 DesiredAccess,
2870 ObjectAttributes,
2871 IoStatusBlock,
2872 AllocationSize,
2873 FileAttributes,
2874 ShareAccess,
2875 Disposition,
2876 CreateOptions,
2877 EaBuffer,
2878 EaLength,
2879 CreateFileType,
2880 ExtraCreateParameters,
2881 Options | IO_NO_PARAMETER_CHECKING,
2882 Flags,
2883 DeviceObject);
2884 }
2885
2886 /*
2887 * @implemented
2888 */
2889 PFILE_OBJECT
2890 NTAPI
2891 IoCreateStreamFileObjectEx(IN PFILE_OBJECT FileObject OPTIONAL,
2892 IN PDEVICE_OBJECT DeviceObject OPTIONAL,
2893 OUT PHANDLE FileObjectHandle OPTIONAL)
2894 {
2895 PFILE_OBJECT CreatedFileObject;
2896 NTSTATUS Status;
2897 HANDLE FileHandle;
2898 OBJECT_ATTRIBUTES ObjectAttributes;
2899 PAGED_CODE();
2900 IOTRACE(IO_FILE_DEBUG, "FileObject: %p\n", FileObject);
2901
2902 /* Choose Device Object */
2903 if (FileObject) DeviceObject = FileObject->DeviceObject;
2904
2905 /* Reference the device object and initialize attributes */
2906 InterlockedIncrement(&DeviceObject->ReferenceCount);
2907 InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
2908
2909 /* Create the File Object */
2910 Status = ObCreateObject(KernelMode,
2911 IoFileObjectType,
2912 &ObjectAttributes,
2913 KernelMode,
2914 NULL,
2915 sizeof(FILE_OBJECT),
2916 sizeof(FILE_OBJECT),
2917 0,
2918 (PVOID*)&CreatedFileObject);
2919 if (!NT_SUCCESS(Status))
2920 {
2921 /* Fail */
2922 IopDereferenceDeviceObject(DeviceObject, FALSE);
2923 ExRaiseStatus(Status);
2924 }
2925
2926 /* Set File Object Data */
2927 RtlZeroMemory(CreatedFileObject, sizeof(FILE_OBJECT));
2928 CreatedFileObject->DeviceObject = DeviceObject;
2929 CreatedFileObject->Type = IO_TYPE_FILE;
2930 CreatedFileObject->Size = sizeof(FILE_OBJECT);
2931 CreatedFileObject->Flags = FO_STREAM_FILE;
2932
2933 /* Initialize the wait event */
2934 KeInitializeEvent(&CreatedFileObject->Event, SynchronizationEvent, FALSE);
2935
2936 /* Insert it to create a handle for it */
2937 Status = ObInsertObject(CreatedFileObject,
2938 NULL,
2939 FILE_READ_DATA,
2940 1,
2941 (PVOID*)&CreatedFileObject,
2942 &FileHandle);
2943 if (!NT_SUCCESS(Status)) ExRaiseStatus(Status);
2944
2945 /* Set the handle created flag */
2946 CreatedFileObject->Flags |= FO_HANDLE_CREATED;
2947 ASSERT(CreatedFileObject->Type == IO_TYPE_FILE);
2948
2949 /* Check if we have a VPB */
2950 if (DeviceObject->Vpb)
2951 {
2952 /* Reference it */
2953 InterlockedIncrement((PLONG)&DeviceObject->Vpb->ReferenceCount);
2954 }
2955
2956 /* Check if the caller wants the handle */
2957 if (FileObjectHandle)
2958 {
2959 /* Return it */
2960 *FileObjectHandle = FileHandle;
2961 ObDereferenceObject(CreatedFileObject);
2962 }
2963 else
2964 {
2965 /* Otherwise, close it */
2966 ObCloseHandle(FileHandle, KernelMode);
2967 }
2968
2969 /* Return the file object */
2970 return CreatedFileObject;
2971 }
2972
2973 /*
2974 * @implemented
2975 */
2976 PFILE_OBJECT
2977 NTAPI
2978 IoCreateStreamFileObject(IN PFILE_OBJECT FileObject,
2979 IN PDEVICE_OBJECT DeviceObject)
2980 {
2981 /* Call the newer function */
2982 return IoCreateStreamFileObjectEx(FileObject, DeviceObject, NULL);
2983 }
2984
2985 /*
2986 * @implemented
2987 */
2988 PFILE_OBJECT
2989 NTAPI
2990 IoCreateStreamFileObjectLite(IN PFILE_OBJECT FileObject OPTIONAL,
2991 IN PDEVICE_OBJECT DeviceObject OPTIONAL)
2992 {
2993 PFILE_OBJECT CreatedFileObject;
2994 NTSTATUS Status;
2995 OBJECT_ATTRIBUTES ObjectAttributes;
2996 PAGED_CODE();
2997 IOTRACE(IO_FILE_DEBUG, "FileObject: %p\n", FileObject);
2998
2999 /* Choose Device Object */
3000 if (FileObject) DeviceObject = FileObject->DeviceObject;
3001
3002 /* Reference the device object and initialize attributes */
3003 InterlockedIncrement(&DeviceObject->ReferenceCount);
3004 InitializeObjectAttributes(&ObjectAttributes, NULL, 0, NULL, NULL);
3005
3006 /* Create the File Object */
3007 Status = ObCreateObject(KernelMode,
3008 IoFileObjectType,
3009 &ObjectAttributes,
3010 KernelMode,
3011 NULL,
3012 sizeof(FILE_OBJECT),
3013 sizeof(FILE_OBJECT),
3014 0,
3015 (PVOID*)&CreatedFileObject);
3016 if (!NT_SUCCESS(Status))
3017 {
3018 /* Fail */
3019 IopDereferenceDeviceObject(DeviceObject, FALSE);
3020 ExRaiseStatus(Status);
3021 }
3022
3023 /* Set File Object Data */
3024 RtlZeroMemory(CreatedFileObject, sizeof(FILE_OBJECT));
3025 CreatedFileObject->DeviceObject = DeviceObject;
3026 CreatedFileObject->Type = IO_TYPE_FILE;
3027 CreatedFileObject->Size = sizeof(FILE_OBJECT);
3028 CreatedFileObject->Flags = FO_STREAM_FILE;
3029
3030 /* Initialize the wait event */
3031 KeInitializeEvent(&CreatedFileObject->Event, SynchronizationEvent, FALSE);
3032
3033 /* Destroy create information */
3034 ObFreeObjectCreateInfoBuffer(OBJECT_TO_OBJECT_HEADER(CreatedFileObject)->
3035 ObjectCreateInfo);
3036 OBJECT_TO_OBJECT_HEADER(CreatedFileObject)->ObjectCreateInfo = NULL;
3037
3038 /* Set the handle created flag */
3039 CreatedFileObject->Flags |= FO_HANDLE_CREATED;
3040 ASSERT(CreatedFileObject->Type == IO_TYPE_FILE);
3041
3042 /* Check if we have a VPB */
3043 if (DeviceObject->Vpb)
3044 {
3045 /* Reference it */
3046 InterlockedIncrement((PLONG)&DeviceObject->Vpb->ReferenceCount);
3047 }
3048
3049 /* Return the file object */
3050 return CreatedFileObject;
3051 }
3052
3053 /*
3054 * @implemented
3055 */
3056 PGENERIC_MAPPING
3057 NTAPI
3058 IoGetFileObjectGenericMapping(VOID)
3059 {
3060 /* Return the mapping */
3061 return &IopFileMapping;
3062 }
3063
3064 /*
3065 * @implemented
3066 */
3067 BOOLEAN
3068 NTAPI
3069 IoIsFileOriginRemote(IN PFILE_OBJECT FileObject)
3070 {
3071 /* Return the flag status */
3072 return FileObject->Flags & FO_REMOTE_ORIGIN ? TRUE : FALSE;
3073 }
3074
3075 /*
3076 * @implemented
3077 */
3078 BOOLEAN
3079 NTAPI
3080 IoFastQueryNetworkAttributes(IN POBJECT_ATTRIBUTES ObjectAttributes,
3081 IN ACCESS_MASK DesiredAccess,
3082 IN ULONG OpenOptions,
3083 OUT PIO_STATUS_BLOCK IoStatus,
3084 OUT PFILE_NETWORK_OPEN_INFORMATION Buffer)
3085 {
3086 NTSTATUS Status;
3087 DUMMY_FILE_OBJECT LocalFileObject;
3088 HANDLE Handle;
3089 OPEN_PACKET OpenPacket;
3090 PAGED_CODE();
3091 IOTRACE(IO_FILE_DEBUG, "FileName: %wZ\n", ObjectAttributes->ObjectName);
3092
3093 /* Setup the Open Packet */
3094 RtlZeroMemory(&OpenPacket, sizeof(OPEN_PACKET));
3095 OpenPacket.Type = IO_TYPE_OPEN_PACKET;
3096 OpenPacket.Size = sizeof(OPEN_PACKET);
3097 OpenPacket.CreateOptions = OpenOptions | FILE_OPEN_REPARSE_POINT;
3098 OpenPacket.ShareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
3099 OpenPacket.Options = IO_FORCE_ACCESS_CHECK;
3100 OpenPacket.Disposition = FILE_OPEN;
3101 OpenPacket.NetworkInformation = Buffer;
3102 OpenPacket.QueryOnly = TRUE;
3103 OpenPacket.FullAttributes = TRUE;
3104 OpenPacket.LocalFileObject = &LocalFileObject;
3105
3106 /*
3107 * Attempt opening the file. This will call the I/O Parse Routine for
3108 * the File Object (IopParseDevice) which will use the dummy file obejct
3109 * send the IRP to its device object. Note that we have two statuses
3110 * to worry about: the Object Manager's status (in Status) and the I/O
3111 * status, which is in the Open Packet's Final Status, and determined
3112 * by the Parse Check member.
3113 */
3114 Status = ObOpenObjectByName(ObjectAttributes,
3115 NULL,
3116 KernelMode,
3117 NULL,
3118 DesiredAccess,
3119 &OpenPacket,
3120 &Handle);
3121 if (OpenPacket.ParseCheck == FALSE)
3122 {
3123 /* Parse failed */
3124 IoStatus->Status = Status;
3125 }
3126 else
3127 {
3128 /* Use the Io status */
3129 IoStatus->Status = OpenPacket.FinalStatus;
3130 IoStatus->Information = OpenPacket.Information;
3131 }
3132
3133 /* Return success */
3134 return TRUE;
3135 }
3136
3137 /*
3138 * @implemented
3139 */
3140 VOID
3141 NTAPI
3142 IoUpdateShareAccess(IN PFILE_OBJECT FileObject,
3143 OUT PSHARE_ACCESS ShareAccess)
3144 {
3145 PAGED_CODE();
3146
3147 /* Check if the file has an extension */
3148 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3149 {
3150 /* Check if caller specified to ignore access checks */
3151 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3152 {
3153 /* Don't update share access */
3154 return;
3155 }
3156 }
3157
3158 /* Otherwise, check if there's any access present */
3159 if ((FileObject->ReadAccess) ||
3160 (FileObject->WriteAccess) ||
3161 (FileObject->DeleteAccess))
3162 {
3163 /* Increase the open count */
3164 ShareAccess->OpenCount++;
3165
3166 /* Add new share access */
3167 ShareAccess->Readers += FileObject->ReadAccess;
3168 ShareAccess->Writers += FileObject->WriteAccess;
3169 ShareAccess->Deleters += FileObject->DeleteAccess;
3170 ShareAccess->SharedRead += FileObject->SharedRead;
3171 ShareAccess->SharedWrite += FileObject->SharedWrite;
3172 ShareAccess->SharedDelete += FileObject->SharedDelete;
3173 }
3174 }
3175
3176 /*
3177 * @implemented
3178 */
3179 NTSTATUS
3180 NTAPI
3181 IoCheckShareAccess(IN ACCESS_MASK DesiredAccess,
3182 IN ULONG DesiredShareAccess,
3183 IN PFILE_OBJECT FileObject,
3184 IN PSHARE_ACCESS ShareAccess,
3185 IN BOOLEAN Update)
3186 {
3187 BOOLEAN ReadAccess;
3188 BOOLEAN WriteAccess;
3189 BOOLEAN DeleteAccess;
3190 BOOLEAN SharedRead;
3191 BOOLEAN SharedWrite;
3192 BOOLEAN SharedDelete;
3193 PAGED_CODE();
3194
3195 /* Get access masks */
3196 ReadAccess = (DesiredAccess & (FILE_READ_DATA | FILE_EXECUTE)) != 0;
3197 WriteAccess = (DesiredAccess & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0;
3198 DeleteAccess = (DesiredAccess & DELETE) != 0;
3199
3200 /* Set them in the file object */
3201 FileObject->ReadAccess = ReadAccess;
3202 FileObject->WriteAccess = WriteAccess;
3203 FileObject->DeleteAccess = DeleteAccess;
3204
3205 /* Check if the file has an extension */
3206 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3207 {
3208 /* Check if caller specified to ignore access checks */
3209 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3210 {
3211 /* Don't check share access */
3212 return STATUS_SUCCESS;
3213 }
3214 }
3215
3216 /* Check if we have any access */
3217 if ((ReadAccess) || (WriteAccess) || (DeleteAccess))
3218 {
3219 /* Get shared access masks */
3220 SharedRead = (DesiredShareAccess & FILE_SHARE_READ) != 0;
3221 SharedWrite = (DesiredShareAccess & FILE_SHARE_WRITE) != 0;
3222 SharedDelete = (DesiredShareAccess & FILE_SHARE_DELETE) != 0;
3223
3224 /* Set them */
3225 FileObject->SharedRead = SharedRead;
3226 FileObject->SharedWrite = SharedWrite;
3227 FileObject->SharedDelete = SharedDelete;
3228
3229 /* Check if the shared access is violated */
3230 if ((ReadAccess &&
3231 (ShareAccess->SharedRead < ShareAccess->OpenCount)) ||
3232 (WriteAccess &&
3233 (ShareAccess->SharedWrite < ShareAccess->OpenCount)) ||
3234 (DeleteAccess &&
3235 (ShareAccess->SharedDelete < ShareAccess->OpenCount)) ||
3236 ((ShareAccess->Readers != 0) && !SharedRead) ||
3237 ((ShareAccess->Writers != 0) && !SharedWrite) ||
3238 ((ShareAccess->Deleters != 0) && !SharedDelete))
3239 {
3240 /* Sharing violation, fail */
3241 return STATUS_SHARING_VIOLATION;
3242 }
3243
3244 /* It's not, check if caller wants us to update it */
3245 if (Update)
3246 {
3247 /* Increase open count */
3248 ShareAccess->OpenCount++;
3249
3250 /* Update shared access */
3251 ShareAccess->Readers += ReadAccess;
3252 ShareAccess->Writers += WriteAccess;
3253 ShareAccess->Deleters += DeleteAccess;
3254 ShareAccess->SharedRead += SharedRead;
3255 ShareAccess->SharedWrite += SharedWrite;
3256 ShareAccess->SharedDelete += SharedDelete;
3257 }
3258 }
3259
3260 /* Validation successful */
3261 return STATUS_SUCCESS;
3262 }
3263
3264 /*
3265 * @implemented
3266 */
3267 VOID
3268 NTAPI
3269 IoRemoveShareAccess(IN PFILE_OBJECT FileObject,
3270 IN PSHARE_ACCESS ShareAccess)
3271 {
3272 PAGED_CODE();
3273
3274 /* Check if the file has an extension */
3275 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3276 {
3277 /* Check if caller specified to ignore access checks */
3278 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3279 {
3280 /* Don't update share access */
3281 return;
3282 }
3283 }
3284
3285 /* Otherwise, check if there's any access present */
3286 if ((FileObject->ReadAccess) ||
3287 (FileObject->WriteAccess) ||
3288 (FileObject->DeleteAccess))
3289 {
3290 /* Decrement the open count */
3291 ShareAccess->OpenCount--;
3292
3293 /* Remove share access */
3294 ShareAccess->Readers -= FileObject->ReadAccess;
3295 ShareAccess->Writers -= FileObject->WriteAccess;
3296 ShareAccess->Deleters -= FileObject->DeleteAccess;
3297 ShareAccess->SharedRead -= FileObject->SharedRead;
3298 ShareAccess->SharedWrite -= FileObject->SharedWrite;
3299 ShareAccess->SharedDelete -= FileObject->SharedDelete;
3300 }
3301 }
3302
3303 /*
3304 * @implemented
3305 */
3306 VOID
3307 NTAPI
3308 IoSetShareAccess(IN ACCESS_MASK DesiredAccess,
3309 IN ULONG DesiredShareAccess,
3310 IN PFILE_OBJECT FileObject,
3311 OUT PSHARE_ACCESS ShareAccess)
3312 {
3313 BOOLEAN ReadAccess;
3314 BOOLEAN WriteAccess;
3315 BOOLEAN DeleteAccess;
3316 BOOLEAN SharedRead;
3317 BOOLEAN SharedWrite;
3318 BOOLEAN SharedDelete;
3319 BOOLEAN Update = TRUE;
3320 PAGED_CODE();
3321
3322 ReadAccess = (DesiredAccess & (FILE_READ_DATA | FILE_EXECUTE)) != 0;
3323 WriteAccess = (DesiredAccess & (FILE_WRITE_DATA | FILE_APPEND_DATA)) != 0;
3324 DeleteAccess = (DesiredAccess & DELETE) != 0;
3325
3326 /* Check if the file has an extension */
3327 if (FileObject->Flags & FO_FILE_OBJECT_HAS_EXTENSION)
3328 {
3329 /* Check if caller specified to ignore access checks */
3330 //if (FileObject->FoExtFlags & IO_IGNORE_SHARE_ACCESS_CHECK)
3331 {
3332 /* Don't update share access */
3333 Update = FALSE;
3334 }
3335 }
3336
3337 /* Update basic access */
3338 FileObject->ReadAccess = ReadAccess;
3339 FileObject->WriteAccess = WriteAccess;
3340 FileObject->DeleteAccess = DeleteAccess;
3341
3342 /* Check if we have no access as all */
3343 if (!(ReadAccess) && !(WriteAccess) && !(DeleteAccess))
3344 {
3345 /* Check if we need to update the structure */
3346 if (!Update) return;
3347
3348 /* Otherwise, clear data */
3349 ShareAccess->OpenCount = 0;
3350 ShareAccess->Readers = 0;
3351 ShareAccess->Writers = 0;
3352 ShareAccess->Deleters = 0;
3353 ShareAccess->SharedRead = 0;
3354 ShareAccess->SharedWrite = 0;
3355 ShareAccess->SharedDelete = 0;
3356 }
3357 else
3358 {
3359 /* Calculate shared access */
3360 SharedRead = (DesiredShareAccess & FILE_SHARE_READ) != 0;
3361 SharedWrite = (DesiredShareAccess & FILE_SHARE_WRITE) != 0;
3362 SharedDelete = (DesiredShareAccess & FILE_SHARE_DELETE) != 0;
3363
3364 /* Set it in the FO */
3365 FileObject->SharedRead = SharedRead;
3366 FileObject->SharedWrite = SharedWrite;
3367 FileObject->SharedDelete = SharedDelete;
3368
3369 /* Check if we need to update the structure */
3370 if (!Update) return;
3371
3372 /* Otherwise, set data */
3373 ShareAccess->OpenCount = 1;
3374 ShareAccess->Readers = ReadAccess;
3375 ShareAccess->Writers = WriteAccess;
3376 ShareAccess->Deleters = DeleteAccess;
3377 ShareAccess->SharedRead = SharedRead;
3378 ShareAccess->SharedWrite = SharedWrite;
3379 ShareAccess->SharedDelete = SharedDelete;
3380 }
3381 }
3382
3383 /*
3384 * @implemented
3385 */
3386 VOID
3387 NTAPI
3388 IoCancelFileOpen(IN PDEVICE_OBJECT DeviceObject,
3389 IN PFILE_OBJECT FileObject)
3390 {
3391 PIRP Irp;
3392 KEVENT Event;
3393 KIRQL OldIrql;
3394 NTSTATUS Status;
3395 PIO_STACK_LOCATION Stack;
3396
3397 /* Check if handles were already created for the
3398 * open file. If so, that's over.
3399 */
3400 if (FileObject->Flags & FO_HANDLE_CREATED)
3401 KeBugCheckEx(INVALID_CANCEL_OF_FILE_OPEN,
3402 (ULONG_PTR)FileObject,
3403 (ULONG_PTR)DeviceObject, 0, 0);
3404
3405 /* Reset the events */
3406 KeInitializeEvent(&Event, SynchronizationEvent, FALSE);
3407 KeClearEvent(&FileObject->Event);
3408
3409 /* Allocate the IRP we'll use */
3410 Irp = IopAllocateIrpMustSucceed(DeviceObject->StackSize);
3411 /* Properly set it */
3412 Irp->Tail.Overlay.Thread = PsGetCurrentThread();
3413 Irp->UserEvent = &Event;
3414 Irp->UserIosb = &Irp->IoStatus;
3415 Irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL;
3416 Irp->Tail.Overlay.OriginalFileObject = FileObject;
3417 Irp->RequestorMode = KernelMode;
3418 Irp->Flags = IRP_CLOSE_OPERATION | IRP_SYNCHRONOUS_API;
3419
3420 Stack = IoGetNextIrpStackLocation(Irp);
3421 Stack->MajorFunction = IRP_MJ_CLEANUP;
3422 Stack->FileObject = FileObject;
3423
3424 /* Put on top of IRPs list of the thread */
3425 IopQueueIrpToThread(Irp);
3426
3427 /* Call the driver */
3428 Status = IoCallDriver(DeviceObject, Irp);
3429 if (Status == STATUS_PENDING)
3430 {
3431 KeWaitForSingleObject(&Event, UserRequest,
3432 KernelMode, FALSE, NULL);
3433 }
3434
3435 /* Remove from IRPs list */
3436 KeRaiseIrql(APC_LEVEL, &OldIrql);
3437 IopUnQueueIrpFromThread(Irp);
3438 KeLowerIrql(OldIrql);
3439
3440 /* Free the IRP */
3441 IoFreeIrp(Irp);
3442
3443 /* Clear the event */
3444 KeClearEvent(&FileObject->Event);
3445 /* And finally, mark the open operation as canceled */
3446 FileObject->Flags |= FO_FILE_OPEN_CANCELLED;
3447 }
3448
3449 /*
3450 * @unimplemented
3451 */
3452 NTSTATUS
3453 NTAPI
3454 IoQueryFileDosDeviceName(IN PFILE_OBJECT FileObject,
3455 OUT POBJECT_NAME_INFORMATION *ObjectNameInformation)
3456 {
3457 UNIMPLEMENTED;
3458 return STATUS_NOT_IMPLEMENTED;
3459 }
3460
3461 /*
3462 * @implemented
3463 */
3464 NTSTATUS
3465 NTAPI
3466 IoSetFileOrigin(IN PFILE_OBJECT FileObject,
3467 IN BOOLEAN Remote