/* schannel_hello.c - probe: does the ClientHello buffer of Schannel stay
   in the process when the caller does not free it?

   Repeats the first step of the TLS handshake of MariaDB Connector/C
   3.4 (libmariadb/secure/schannel.c, ma_tls_connect, and
   ma_schannel.c, ma_schannel_client_handshake) on Windows 10:
   AcquireCredentialsHandle with the legacy SCHANNEL_CRED structure and
   the same flags, InitializeSecurityContext with ISC_REQ_ALLOCATE_MEMORY,
   then DeleteSecurityContext and FreeCredentialsHandle as in
   ma_tls_close.  No network and no server are needed: the first call
   only builds the ClientHello.

   Mode "leak" omits FreeContextBuffer on the output buffer, as the
   success path of ma_schannel_client_handshake does; mode "free" calls
   it.  The program prints the size of the ClientHello and the private
   bytes of the process.

   Usage: schannel_hello leak|free [COUNT [TARGET]]
     COUNT   iterations, default 20000
     TARGET  target name passed to InitializeSecurityContext,
             default 127.0.0.1 (the host of the DSN)

   Build (x64 Native Tools prompt with oneAPI):
     icx /nologo /W4 /O2 schannel_hello.c secur32.lib psapi.lib  */

#define _CRT_SECURE_NO_WARNINGS
#define SECURITY_WIN32
#include <windows.h>
#include <wincrypt.h>
#include <security.h>
#include <schannel.h>
#include <psapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define REPORT_EVERY 1000

static SIZE_T
private_bytes (void)
{
  PROCESS_MEMORY_COUNTERS_EX pmc;

  memset (&pmc, 0, sizeof (pmc));
  pmc.cb = sizeof (pmc);
  if (!GetProcessMemoryInfo (GetCurrentProcess (),
                             (PROCESS_MEMORY_COUNTERS *) &pmc,
                             sizeof (pmc)))
    return 0;
  return pmc.PrivateUsage;
}

/* One ClientHello as in ma_tls_connect and ma_schannel_client_handshake.
   Returns the size of the ClientHello, or 0 on an error.  */
static DWORD
one_hello (int do_free, char *target)
{
  SCHANNEL_CRED cred;
  CredHandle hcred;
  CtxtHandle hctxt;
  SecBufferDesc out_desc;
  SecBuffer out_buf;
  SECURITY_STATUS rc;
  DWORD out_flags = 0;
  DWORD size;
  DWORD sflags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT
    | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR
    | ISC_REQ_USE_SUPPLIED_CREDS | ISC_REQ_ALLOCATE_MEMORY
    | ISC_REQ_STREAM;

  /* init_auth_data: legacy structure before Windows Server 2022 or
     Windows 11, no protocol and no cipher given.  */
  memset (&cred, 0, sizeof (cred));
  cred.dwVersion = SCHANNEL_CRED_VERSION;
  cred.grbitEnabledProtocols = 0;
  cred.dwFlags = SCH_CRED_NO_SERVERNAME_CHECK | SCH_CRED_NO_DEFAULT_CREDS
    | SCH_CRED_MANUAL_CRED_VALIDATION;

  SecInvalidateHandle (&hcred);
  SecInvalidateHandle (&hctxt);

  rc = AcquireCredentialsHandleA (NULL, UNISP_NAME_A, SECPKG_CRED_OUTBOUND,
                                  NULL, &cred, NULL, NULL, &hcred, NULL);
  if (rc != SEC_E_OK)
    {
      fprintf (stderr, "AcquireCredentialsHandle: 0x%08lx\n",
               (unsigned long) rc);
      return 0;
    }

  out_buf.BufferType = SECBUFFER_TOKEN;
  out_buf.cbBuffer = 0;
  out_buf.pvBuffer = NULL;
  out_desc.cBuffers = 1;
  out_desc.pBuffers = &out_buf;
  out_desc.ulVersion = SECBUFFER_VERSION;

  rc = InitializeSecurityContextA (&hcred, NULL, target, sflags, 0,
                                   SECURITY_NATIVE_DREP, NULL, 0, &hctxt,
                                   &out_desc, &out_flags, NULL);
  if (rc != SEC_I_CONTINUE_NEEDED)
    {
      fprintf (stderr, "InitializeSecurityContext: 0x%08lx\n",
               (unsigned long) rc);
      FreeCredentialsHandle (&hcred);
      return 0;
    }
  size = out_buf.cbBuffer;

  /* ma_schannel_client_handshake frees this buffer only on its error
     path; on success it returns without FreeContextBuffer.  */
  if (do_free && out_buf.pvBuffer)
    FreeContextBuffer (out_buf.pvBuffer);

  /* ma_tls_close */
  if (SecIsValidHandle (&hcred))
    FreeCredentialsHandle (&hcred);
  if (SecIsValidHandle (&hctxt))
    DeleteSecurityContext (&hctxt);
  return size;
}

int
main (int argc, char **argv)
{
  int do_free;
  long count = 20000;
  char *target = "127.0.0.1";
  long i;
  DWORD size = 0;
  SIZE_T base = 0;
  SIZE_T now;

  if (argc < 2
      || (strcmp (argv[1], "leak") != 0 && strcmp (argv[1], "free") != 0))
    {
      fprintf (stderr, "usage: %s leak|free [COUNT [TARGET]]\n", argv[0]);
      return 2;
    }
  do_free = strcmp (argv[1], "free") == 0;
  if (argc > 2)
    count = strtol (argv[2], NULL, 10);
  if (argc > 3)
    target = argv[3];
  if (count < 2 * REPORT_EVERY)
    count = 2 * REPORT_EVERY;

  printf ("mode %s, %ld iterations, target \"%s\"\n",
          do_free ? "free" : "leak", count, target);

  for (i = 1; i <= count; i++)
    {
      DWORD s = one_hello (do_free, target);

      if (s == 0)
        return 1;
      if (size == 0)
        {
          size = s;
          printf ("ClientHello size %lu bytes\n", (unsigned long) size);
        }
      else if (s != size)
        printf ("iteration %ld: ClientHello size %lu bytes\n", i,
                (unsigned long) s);

      if (i % REPORT_EVERY == 0)
        {
          now = private_bytes ();
          if (i == REPORT_EVERY)
            {
              base = now;
              printf ("%7ld  private %10zu  (baseline)\n", i, now);
            }
          else
            printf ("%7ld  private %10zu  %+8.1f bytes per iteration\n",
                    i, now,
                    ((double) now - (double) base)
                    / (double) (i - REPORT_EVERY));
        }
    }
  return 0;
}
