
#include <ntddk.h>
#include "version.h"
#include "lists.h"
#include "hash_table.h"
#include "events.h"
#include "ioctls.h"
#include "regevents.h"
#include "regcallback.h"
#include "driver.h"


/** Obsluha volani funkci Windows API CreateFile a Closehandle na nase
 *  komunikacni zarizeni. 
 *
 * Instruujeme system, ze obsluha pozadavku je
 * ukoncena a vratime uspech (STATUS_SUCCESS).
 *
 * @param DeviceObject Struktura DEVICE_OBJECT, ktera reprezentuje nase 
 *   zarizeni.
 * @param Irp Pozadavek na nase zarizeni (vygenerovany volanim CreateFile,
 *   nebo CloseHandle).
 */
NTSTATUS DriverCreateClose(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
  NTSTATUS Status = STATUS_UNSUCCESSFUL;
  KdPrint(("driver.c: DriverCreateClose(DeviceObject=0x%p; Irp=0x%p)\n", DeviceObject, Irp));

  // Upozornime system, aby povazoval pozadavek (IRP) za obslouzeny a vratime uspech
  IoCompleteRequest(Irp,IO_NO_INCREMENT);
  Status = STATUS_SUCCESS;

  KdPrint(("driver.c: DriverCreateClose(-):0x%x\n", Status));
  return Status;
}


/** Obsluha volani funkce Windows API DeviceIoControlFile na nase komunikacni
 *  zarizeni.
 *
 * Tato rutina se vyvola, kdykoliv nejaka aplikace zavola funkci DeviceIoControl
 * a posle tak pozadavek nasemu zarizeni. DeviceIoControl je cesta, kterou muze
 * s nasim ovladacem komunikovat libovolna aplikace.
 *
 * Ovladac podporuje pouze jeden druh pozadavku - pozadavek na vraceni zaznamenane
 * udalosti ze zivota procesu, vlaken ci modulu (knihoven DLL a ovladacu jadra).
 * 
 * Pokud je seznam prazdny, rutina vrati chybu STATUS_NO_MORE_ENTRIES. Pokud
 * seznam udalosti neni prazdny a zadajici aplikace poskytuje dostatecne velky
 * buffer pro zapsani udalosti, prvni udalost se odebere ze seznamu a zkopiruje
 * do vystupniho bufferu. Je-li velikost bufferu nedostatecna, rutina vrati chybu
 * STATUS_BUFFER_TOO_SMALL.
 *
 * @param DeviceObject Struktura DEVICE_OBJECT reprezentujici nase zarizeni.
 * @param Pozadavek od volajici aplikace (vygenerovany volanim DeviceIoControl).
 */
NTSTATUS DriverDeviceControl(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
  NTSTATUS Status = STATUS_UNSUCCESSFUL;
  PIO_STACK_LOCATION IrpStack = NULL;
  PVOID OutBuffer = NULL;
  ULONG OutBufferLength = 0;
  ULONG ControlCode = 0;
  KdPrint(("driver.c: DriverDeviceControl(DeviceObject=0x%p ;Irp=0x%p)\n", DeviceObject, Irp));

  /* Zjistime adresu a velikost vystupniho bufferu a kod zpravy, kterou
     aplikace posila. Velikost vstupniho bufferu nema smysl zjistovat, 
     protoze veskere potrebne informace dostaneme v kodu zpravy.
   */
  IrpStack = IoGetCurrentIrpStackLocation(Irp);
  OutBufferLength = IrpStack->Parameters.DeviceIoControl.OutputBufferLength;
  OutBuffer = Irp->AssociatedIrp.SystemBuffer;
  ControlCode = IrpStack->Parameters.DeviceIoControl.IoControlCode;
  Irp->IoStatus.Information = 0;

  // Zjistime, o ktery prikaz se jedna
  switch (ControlCode)
  {
    // Poslat aplikaci prvni zpravu ze seznamu udalosti
    case IOCTL_REGISTRYMON_GET_EVENT:
    {
      KLOCK_QUEUE_HANDLE QHandle;
      PEVENT u = EventGetFirst();
      PUM_EVENT um = (PUM_EVENT)OutBuffer;

      EventListLock(&QHandle);
      if (u != NULL) {
        if (OutBufferLength >= sizeof(UM_EVENT) + u->Size - sizeof(EVENT)) {
          um->Time = u->Time;
          um->Type = u->Type;
          um->Size = u->Size + sizeof(UM_EVENT) - sizeof(EVENT);
          RtlCopyMemory(UM_EVENT_TO_DATA(um), EVENT_TO_DATA(u), u->Size - sizeof(EVENT));
          Irp->IoStatus.Information = um->Size;
          Status = STATUS_SUCCESS;
          EventFree(u);
        } else {
          EventInsertFirst(u);
          Status = STATUS_BUFFER_TOO_SMALL;
        }
      } else Status = STATUS_NO_MORE_ENTRIES;

      EventListUnlock(&QHandle);
    }
      break;

    // Jine pozadavky ovladac neobsluhuje, nejsou implementovany
    default:
      KdPrint(("driver.c: DriverDeviceControl(): Chybny kod pozadavku!\n"));
      Status = STATUS_NOT_IMPLEMENTED;
      break;
  }  

  // Sdelime systemu, ze pozadavek aplikace je obslouzen
  Irp->IoStatus.Status = Status;
  IoCompleteRequest(Irp, IO_NO_INCREMENT);

  KdPrint(("driver.c: DriverDeviceControl(-):0x%x\n", Status));
  return Status;
}



/** Odstrani komunikacni zarizeni ovladace a jeho symbolicky odkaz.
 *
 *  @param DriverObject Adresa struktury DRIVER_OBJECT, ktera reprezentuje
 *  ovladac registrymon.sys.
 */
VOID DriverFinit(PDRIVER_OBJECT DriverObject)
{
  UNICODE_STRING usymlink;
  KdPrint(("driver.c: DriverFinit(DriverObject=0x%p)\n", DriverObject));

  RtlInitUnicodeString(&usymlink, REGISTRYMON_SYMLINK);
  IoDeleteSymbolicLink(&usymlink);
  IoDeleteDevice(DriverObject->DeviceObject);

  KdPrint(("driver.c: DriverFinit(-)\n"));
  return;
}


/** Tato rutina je volana tesne pred uvolnenim ovladace z jadra. Zajisti
 *  uklid vsech soucasti ovladace vcetne komunikacniho mechanismu.
 */
VOID DriverUnload(IN PDRIVER_OBJECT DriverObject)
{
  KdPrint(("driver.c: DriverUnload(DriverObject=0x%p)\n", DriverObject));

  DriverFinit(DriverObject);
  RegEventsFinit();
  RegCallbackFinit();
  EventsFinit();
  VersionFinit();

  KdPrint(("driver.c: DriverUnload(-)\n"));
  return;
}

/** Vytvori komunikacni zarizeni ovladace a nasmeruje na nej symbolicky
 *  odkaz.
 *
 *  @param DriverObject Adresa struktury DRIVER_OBJECT, ktera reprezentuje
 *  ovladac registrymon.sys.
 */
NTSTATUS DriverInit(PDRIVER_OBJECT DriverObject)
{
  UNICODE_STRING usymlink;
  UNICODE_STRING udevice;
  NTSTATUS Status = STATUS_UNSUCCESSFUL;
  KdPrint(("driver.c: DriverInit(DriverObject=0x%p)\n", DriverObject));

  RtlInitUnicodeString(&udevice, REGISTRYMON_DEVICE);
  Status = IoCreateDevice(DriverObject, 0, &udevice, FILE_DEVICE_UNKNOWN, 0, FALSE, &DriverObject->DeviceObject);
  if (NT_SUCCESS(Status)) {
    // Komunikacni zarizeni bylo vytvoreno v oblasti, do ktere normalni aplikace
    // nemaji za vyuziti dokumentovanych prostredku pristup. Zarizeni zpristupnime
    // vytvorenim symbolickeho odkazu
    RtlInitUnicodeString(&usymlink, REGISTRYMON_SYMLINK);
    Status = IoCreateSymbolicLink(&usymlink, &udevice);
    if (NT_SUCCESS(Status)) {
      // Nastavime rutinu, kterou ma system zavolat pri odstranovani ovladace
      // z jadra. Neni-li tato rutina nastavena, ovladac nelze z jadra odstranit
      DriverObject->DriverUnload = DriverUnload;

      // Nastavime funkce, ktere system preda rizeni, kdykoliv nejaka aplikace
      // zavola CreateFile ci CloseHandle na nase zarizeni
      DriverObject->MajorFunction[IRP_MJ_CREATE] = DriverCreateClose;
      DriverObject->MajorFunction[IRP_MJ_CLOSE] = DriverCreateClose;

      // Nase odpoved na volani DeviceIoControl
      DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DriverDeviceControl;
	} else IoDeleteDevice(DriverObject->DeviceObject);
  }

  KdPrint(("driver.c: DriverInit(-):0x%x\n", Status));
  return Status;
}


/** Tato rutina je volana tesne po namapovani ovladace do pameti jadra.
 *  Zajisti inicializaci vsech jeho soucasti a vytvoreni komunikacniho
 *  zarizeni.
 */
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{
  NTSTATUS Status = STATUS_UNSUCCESSFUL;
  KdPrint(("driver.c: DriverEntry(DriverObject=0x%p; RegistryPath=\"%S\"", DriverObject, RegistryPath));

  Status = VersionInit();
  if (NT_SUCCESS(Status)) {
    Status = EventsInit();
    if (NT_SUCCESS(Status)) {
      Status = RegCallbackInit();
      if (NT_SUCCESS(Status)) {
        Status = RegEventsInit();
        if (NT_SUCCESS(Status)) {
          Status = DriverInit(DriverObject);
          if (!NT_SUCCESS(Status)) {
            RegEventsFinit();
            RegCallbackFinit();
            EventsFinit();
            VersionFinit();
          }
        } else {
          RegCallbackFinit();
          EventsFinit();
          VersionFinit();
        }
      } else {
        EventsFinit();
        VersionFinit();
      }
    } else VersionFinit();
  }

  KdPrint(("driver.c: DriverEntry(-):0x%x\n", Status));
  return Status;
}
