using System;
using System.Runtime.InteropServices;

namespace Waffle.Windows.AuthProvider
{
    /// <summary>
    /// Secure32.dll PInvoke.
    /// </summary>
    public abstract class Secur32
    {
        /// <summary>
        /// Maximum size in bytes of a securit token.
        /// </summary>
        public const int MAX_TOKEN_SIZE = 12288;

        // Return codes for secur32 fuctions

        /// <summary>
        /// The function succeeded. The security context received from the client was accepted. If an output token was generated by the function, it must be sent to the client process.
        /// </summary>
        public const int SEC_E_OK = 0;

        /// <summary>
        /// The function failed. The handle passed to the function is not valid.
        /// </summary>
        public const int SEC_E_INVALID_HANDLE = unchecked((int)0x80100003);

        /// <summary>
        /// The function failed. The token passed to the function is not valid.
        /// </summary>
        public const int SEC_E_INVALID_TOKEN = unchecked((int)0x80090308);

        /// <summary>
        /// The function failed. There is not enough memory available to complete the requested action.
        /// </summary>
        public const int SEC_E_INSUFFICIENT_MEMORY = unchecked((int)0x80090300);

        /// <summary>
        /// The function failed. The supplied buffer is too small.
        /// </summary>
        public const int SEC_E_BUFFER_TOO_SMALL = unchecked((int)0x80090321);

        /// <summary>
        /// The function failed. An error occurred that did not map to an SSPI error code.
        /// </summary>
        public const int SEC_E_INTERNAL_ERROR = unchecked((int)0x80090304);

        /// <summary>
        /// The logon failed.
        /// </summary>
        public const int SEC_E_LOGON_DENIED = unchecked((int)0x8009030C);

        /// <summary>
        /// The function failed. No authority could be contacted for authentication. This could be due to the following conditions:
        ///  - The domain name of the authenticating party is incorrect.
        ///  - The domain is unavailable.
        ///  - The trust relationship has failed.
        /// </summary>
        public const int SEC_E_NO_AUTHENTICATING_AUTHORITY = unchecked((int)0x80090311);

        /// <summary>
        /// The function succeeded. The server must send the output token to the client and wait for a returned token. The returned token should be passed in pInput for another call to AcceptSecurityContext (Negotiate).
        /// </summary>
        public const int SEC_I_CONTINUE_NEEDED = 0x90312;


        // Flags for the fCredentialUse parameter of AcquireCredentialsHandle

        /// <summary>
        /// Validate an incoming server credential. Inbound credentials might be validated by using 
        /// an authenticating authority when InitializeSecurityContext or
        /// AcceptSecurityContext is called. If such an authority is not available, the function will 
        /// fail and return SEC_E_NO_AUTHENTICATING_AUTHORITY. Validation is package specific.
        /// </summary>
        public const int SECPKG_CRED_INBOUND = 1;

        /// <summary>
        /// Allow a local client credential to prepare an outgoing token.
        /// </summary>
        public const int SECPKG_CRED_OUTBOUND = 2;

        
        // Flags for the TargetDataRep parameter of AcceptSecurityContext and InitializeSecurityContext

        /// <summary>
        /// Specifies Native data representation. 
        /// </summary>
        public const int SECURITY_NATIVE_DREP = 0x10;


        // Flags for the fContextReq parameter of InitializeSecurityContext or AcceptSecurityContext.

        /// <summary>
        /// The security package allocates output buffers for you. 
        /// When you have finished using the output buffers, free them by calling the FreeContextBuffer function.
        /// </summary>
        public const int ISC_REQ_ALLOCATE_MEMORY = 0x00000100;

        /// <summary>
        /// Encrypt messages by using the EncryptMessage function.
        /// </summary>
        public const int ISC_REQ_CONFIDENTIALITY = 0x00000010;

        /// <summary>
        /// The security context will not handle formatting messages. This value is the default.
        /// </summary>
        public const int ISC_REQ_CONNECTION = 0x00000800;

        /// <summary>
        /// The server can use the context to authenticate to other servers as the client. 
        /// The ISC_REQ_MUTUAL_AUTH flag must be set for this flag to work. Valid for Kerberos. 
        /// Ignore this flag for constrained delegation.
        /// </summary>
        public const int ISC_REQ_DELEGATE = 0x00000001;

        /// <summary>
        /// When errors occur, the remote party will be notified.
        /// </summary>
        public const int ISC_REQ_EXTENDED_ERROR = 0x00004000;

        /// <summary>
        /// Sign messages and verify signatures by using the EncryptMessage and MakeSignature functions.
        /// </summary>
        public const int ISC_REQ_INTEGRITY = 0x00010000;

        /// <summary>
        /// The mutual authentication policy of the service will be satisfied.
        /// </summary>
        public const int ISC_REQ_MUTUAL_AUTH = 0x00000002;

        /// <summary>
        /// Detect replayed messages that have been encoded by using the 
        /// EncryptMessage or MakeSignature functions.
        /// </summary>
        public const int ISC_REQ_REPLAY_DETECT = 0x00000004;

        /// <summary>
        /// Detect messages received out of sequence.
        /// </summary>
        public const int ISC_REQ_SEQUENCE_DETECT = 0x00000008;

        /// <summary>
        /// Support a stream-oriented connection.
        /// </summary>
        public const int ISC_REQ_STREAM = 0x00008000;

        /// <summary>
        /// 
        /// </summary>
        public const int ISC_REQ_USE_SUPPLIED_CREDS = 0x00000080;

        /// <summary>
        /// Version of the SecBuffer struct.
        /// </summary>
        public const int SECBUFFER_VERSION = 0;

        /// <summary>
        /// ANSI Identity.
        /// </summary>
        public const int SEC_WINNT_AUTH_IDENTITY_ANSI = 0x1;

        /// <summary>
        /// Unicode Identity.
        /// </summary>
        public const int SEC_WINNT_AUTH_IDENTITY_UNICODE = 0x2;

        /// <summary>
        /// A Windows auth identity.
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct SEC_WINNT_AUTH_IDENTITY
        {
            /// <summary>
            /// A Windows auth identity
            /// </summary>
            /// <param name="username">Username.</param>
            /// <param name="domain">Domain.</param>
            /// <param name="password">Password.</param>
            public SEC_WINNT_AUTH_IDENTITY(string username, string domain, string password)
            {
                User = username;
                UserLength = (username == null ? 0 : username.Length);
                Domain = domain;
                DomainLength = (domain == null ? 0 : domain.Length);
                Password = password;
                PasswordLength = (password == null ? 0 : password.Length);
                Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
            }

            /// <summary>
            /// A string that contains the user name.
            /// </summary>
            public string User;
            /// <summary>
            /// The length, in characters, of the user string, not including the terminating null character.
            /// </summary>
            public int UserLength;
            /// <summary>
            /// A string that contains the domain name or the workgroup name.
            /// </summary>
            public string Domain;
            /// <summary>
            /// The length, in characters, of the domain string, not including the terminating null character.
            /// </summary>
            public int DomainLength;
            /// <summary>
            /// A string that contains the password of the user in the domain or workgroup.
            /// </summary>
            public string Password;
            /// <summary>
            /// The length, in characters, of the password string, not including the terminating null character.
            /// </summary>
            public int PasswordLength;
            /// <summary>
            /// Flags.
            /// </summary>
            public int Flags;
        };

        /// <summary>
        /// SECURITY_INTEGER is a structure that holds a numeric value. It is used in defining other types.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_INTEGER
        {
            /// <summary>
            /// Least significant digits.
            /// </summary>
            public uint LowPart;

            /// <summary>
            /// Most significant digits
            /// </summary>
            public int HighPart;

            /// <summary>
            /// Zero integer.
            /// </summary>
            public static SECURITY_INTEGER Zero;

            /// <summary>
            /// Static constructor for SECURITY_INTEGER.Zero;
            /// </summary>
            static SECURITY_INTEGER()
            {
                Zero.LowPart = 0;
                Zero.HighPart = 0;
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <returns></returns>
            public static bool operator !=(SECURITY_INTEGER value1, SECURITY_INTEGER value2)
            {
                return !value1.Equals(value2);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <returns></returns>
            public static bool operator ==(SECURITY_INTEGER value1, SECURITY_INTEGER value2)
            {
                return value1.Equals(value2);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public override bool Equals(object obj)
            {
                if (obj is SECURITY_INTEGER)
                {
                    SECURITY_INTEGER secHandle = (SECURITY_INTEGER)obj;
                    return secHandle.HighPart == HighPart
                        && secHandle.LowPart == LowPart;
                }

                return base.Equals(obj);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
        };

        /// <summary>
        /// SSPI uses the following handle types and pointers to these handles:
        ///  SecHandle and PSecHandle 
        ///  CredHandle and PCredHandle 
        ///  CtxtHandle and PCtxtHandle 
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct SecHandle
        {
            /// <summary>
            /// Least significant digits.
            /// </summary>
            public IntPtr LowPart;
            /// <summary>
            /// Most significant digits
            /// </summary>
            public IntPtr HighPart;

            /// <summary>
            /// Zero handle.
            /// </summary>
            public static SecHandle Zero;
            
            /// <summary>
            /// Static constructor for Zero SecHandle.
            /// </summary>
            static SecHandle()
            {
                Zero.HighPart = IntPtr.Zero;
                Zero.LowPart = IntPtr.Zero;
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <returns></returns>
            public static bool operator !=(SecHandle value1, SecHandle value2)
            {
                return !value1.Equals(value2);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <returns></returns>
            public static bool operator ==(SecHandle value1, SecHandle value2)
            {
                return value1.Equals(value2);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public override bool Equals(object obj)
            {
                if (obj is SecHandle)
                {
                    SecHandle secHandle = (SecHandle) obj;
                    return secHandle.HighPart == HighPart
                        && secHandle.LowPart == LowPart;
                }

                return base.Equals(obj);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
        };

        /// <summary>
        /// The possible types of the SecBuffer
        /// </summary>
        public enum SecBufferType : int
        {
            /// <summary>
            /// This is a placeholder in the buffer array.
            /// </summary>
            SECBUFFER_EMPTY = 0,

            /// <summary>
            /// This buffer type is used for common data. The security package can read and write this data.
            /// </summary>
            SECBUFFER_DATA = 1,

            /// <summary>
            /// This buffer type is used to indicate the security token portion of the message. This is read-only for input parameters or read/write for output parameters.
            /// </summary>
            SECBUFFER_TOKEN = 2
        }

        /// <summary>
        /// The SecBuffer structure describes a buffer allocated by a transport application to pass to a security package.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct SecBuffer : IDisposable
        {
            /// <summary>
            /// Specifies the size, in bytes, of the buffer pointed to by the pvBuffer member.
            /// </summary>
            public int cbBuffer;

            /// <summary>
            /// Bit flags that indicate the type of buffer. Must be one of the values of the SecBufferType enumeration.
            /// </summary>
            public SecBufferType BufferType;

            /// <summary>
            /// A pointer to a buffer.
            /// </summary>
            public IntPtr pvBuffer;

            /// <summary>
            /// Constructs a SecBuffer of teh specified size.
            /// </summary>
            /// <param name="bufferSize">Buffer size.</param>
            public SecBuffer(int bufferSize)
            {
                cbBuffer = bufferSize;
                BufferType = SecBufferType.SECBUFFER_TOKEN;
                pvBuffer = Marshal.AllocHGlobal(bufferSize);
            }

            /// <summary>
            /// Construct a SecBuffer from the byte array representation secBufferBytes.
            /// </summary>
            /// <param name="secBufferBytes">byte array representation of a SecBuffer</param>
            public SecBuffer(byte[] secBufferBytes)
            {
                BufferType = SecBufferType.SECBUFFER_TOKEN;
                if (secBufferBytes != null)
                {
                    cbBuffer = secBufferBytes.Length;                    
                    pvBuffer = Marshal.AllocHGlobal(cbBuffer);
                    Marshal.Copy(secBufferBytes, 0, pvBuffer, cbBuffer);
                }
                else
                {
                    cbBuffer = 0;
                    pvBuffer = IntPtr.Zero;
                }
            }

            /// <summary>
            /// Free the memory used by the SecBuffer
            /// </summary>
            public void Dispose()
            {
                if (pvBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pvBuffer);
                    pvBuffer = IntPtr.Zero;
                }
            }
        }

        /// <summary>
        /// Describes an array of SecBuffer structures to pass from a transport application to a security package.
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct SecBufferDesc : IDisposable
        {
            /// <summary>
            /// Specifies the version number of this structure. This member must be SECBUFFER_VERSION.
            /// </summary>
            public int ulVersion;

            /// <summary>
            /// Indicates the number of SecBuffer structures in the pBuffers array
            /// </summary>
            public int cBuffers;

            /// <summary>
            /// Pointer to an array of SecBuffer structure
            /// </summary>
            public IntPtr pBuffers;

            /// <summary>
            /// Creates a SecBufferDesc struct with a single empty SecBuffer.
            /// </summary>
            /// <param name="bufferSize">Size of the SecBuffer</param>
            public SecBufferDesc(int bufferSize)
            {
                ulVersion = SECBUFFER_VERSION;
                cBuffers = 1;
                SecBuffer ThisSecBuffer = new SecBuffer(bufferSize);
                pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(ThisSecBuffer));
                Marshal.StructureToPtr(ThisSecBuffer, pBuffers, false);
            }

            /// <summary>
            /// Constructs a SecBufferDesc with a single SecBuffer initialized from the
            /// byte array secBufferBytes.
            /// </summary>
            /// <param name="secBufferBytes">The SecBuffer to add to this SecBufferDesc</param>
            public SecBufferDesc(byte[] secBufferBytes)
            {
                ulVersion = SECBUFFER_VERSION;
                cBuffers = 1;
                SecBuffer ThisSecBuffer = new SecBuffer(secBufferBytes);
                pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(ThisSecBuffer));
                Marshal.StructureToPtr(ThisSecBuffer, pBuffers, false);
            }

            /// <summary>
            /// Dispose the SecBufferDesc and all the SecBuffers it contains.
            /// </summary>
            public void Dispose()
            {
                if (pBuffers != IntPtr.Zero)
                {
                    if (cBuffers == 1)
                    {
                        SecBuffer ThisSecBuffer = (SecBuffer)Marshal.PtrToStructure(pBuffers, typeof(SecBuffer));
                        ThisSecBuffer.Dispose();
                    }
                    else
                    {
                        for (int Index = 0; Index < cBuffers; Index++)
                        {
                            int currentOffset = Index * Marshal.SizeOf(typeof(SecBuffer));
                            IntPtr secBufferpvBuffer = Marshal.ReadIntPtr(pBuffers, currentOffset + Marshal.SizeOf(typeof(int)) + Marshal.SizeOf(typeof(int)));
                            Marshal.FreeHGlobal(secBufferpvBuffer);
                        }
                    }

                    Marshal.FreeHGlobal(pBuffers);
                    pBuffers = IntPtr.Zero;
                }
            }

            /// <summary>
            /// Marshals all the SecBuffers into a byte array.
            /// </summary>
            /// <returns>Byte array representation of all the SecBuffers contained in this SecBufferDesc</returns>
            public byte[] GetSecBufferByteArray()
            {
                byte[] buffer = null;

                if (pBuffers == IntPtr.Zero)
                {
                    throw new ObjectDisposedException("pBuffers");
                }

                if (cBuffers == 1)
                {
                    SecBuffer ThisSecBuffer = (SecBuffer)Marshal.PtrToStructure(pBuffers, typeof(SecBuffer));

                    if (ThisSecBuffer.cbBuffer > 0)
                    {
                        buffer = new byte[ThisSecBuffer.cbBuffer];
                        Marshal.Copy(ThisSecBuffer.pvBuffer, buffer, 0, ThisSecBuffer.cbBuffer);
                    }
                }
                else
                {
                    int bytesToAllocate = 0;

                    // The bits were written out the following order:
                    //  int cbBuffer;
                    //  int BufferType;
                    //  pvBuffer;

                    // calculate the total size of the buffer
                    for (int Index = 0; Index < cBuffers; Index++)
                    {
                        int currentOffset = Index * Marshal.SizeOf(typeof(SecBuffer));
                        bytesToAllocate += Marshal.ReadInt32(pBuffers, currentOffset);
                    }

                    buffer = new byte[bytesToAllocate];

                    // copy to the destination buffer
                    for (int Index = 0, bufferIndex = 0; Index < cBuffers; Index++)
                    {
                        int currentOffset = Index * Marshal.SizeOf(typeof(SecBuffer));
                        int bytesToCopy = Marshal.ReadInt32(pBuffers, currentOffset);
                        IntPtr secBufferpvBuffer = Marshal.ReadIntPtr(pBuffers, currentOffset + Marshal.SizeOf(typeof(int)) + Marshal.SizeOf(typeof(int)));
                        Marshal.Copy(secBufferpvBuffer, buffer, bufferIndex, bytesToCopy);
                        bufferIndex += bytesToCopy;
                    }
                }

                return buffer;
            }

            /// <summary>
            /// Empty security buffer descriptor.
            /// </summary>
            public static SecBufferDesc Zero;

            static SecBufferDesc()
            {
                Zero.cBuffers = 0;
                Zero.pBuffers = IntPtr.Zero;
                Zero.ulVersion = SECBUFFER_VERSION;
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <returns></returns>
            public static bool operator !=(SecBufferDesc value1, SecBufferDesc value2)
            {
                return ! value1.Equals(value2);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <returns></returns>
            public static bool operator ==(SecBufferDesc value1, SecBufferDesc value2)
            {
                return value1.Equals(value2);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public override bool Equals(object obj)
            {
                if (obj is SecBufferDesc)
                {
                    SecBufferDesc secBufferDesc = (SecBufferDesc) obj;
                    return cBuffers == secBufferDesc.cBuffers
                        && pBuffers == secBufferDesc.pBuffers
                        && ulVersion == secBufferDesc.ulVersion;
                }

                return base.Equals(obj);
            }

            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
            public override int GetHashCode()
            {
                return pBuffers.GetHashCode();
            }
        }

        /// <summary>
        /// Enables the server component of a transport application to establish a security context 
        /// between the server and a remote client. The remote client uses the InitializeSecurityContext 
        /// function to start the process of establishing a security context. 
        /// The server can require one or more reply tokens from the remote client to complete establishing
        /// the security context.
        /// </summary>
        /// <param name="phCredential">A handle to the credentials of the server. The server calls the AcquireCredentialsHandle (Negotiate) function with either the SECPKG_CRED_INBOUND or SECPKG_CRED_BOTH flag set to retrieve this handle.</param>
        /// <param name="phContext">A pointer to a CtxtHandle structure. On the first call to AcceptSecurityContext (Negotiate), this pointer is NULL. On subsequent calls, phContext is the handle to the partially formed context that was returned in the phNewContext parameter by the first call.</param>
        /// <param name="pInput">A pointer to a SecBufferDesc structure generated by a client call to InitializeSecurityContext (Negotiate) that contains the input buffer descriptor.</param>
        /// <param name="fContextReq">Bit flags that specify the attributes required by the server to establish the context.</param>
        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target. SECURITY_NATIVE_DREP or SECURITY_NETWORK_DREP</param>
        /// <param name="phNewContext">A pointer to a CtxtHandle structure.</param>
        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the output buffer descriptor. This buffer is sent to the client for input into additional calls to InitializeSecurityContext.</param>
        /// <param name="pfContextAttr">A pointer to a variable that receives a set of bit flags that indicate the attributes of the established context.</param>
        /// <param name="ptsTimeStamp">A pointer to a TimeStamp structure that receives the expiration time of the context.</param>
        /// <returns>Returns SEC_E_OK when the security context from the client is accepted.</returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int AcceptSecurityContext(
            [In] ref SecHandle phCredential,
            [In][Out] ref SecHandle phContext,
            [In] ref SecBufferDesc pInput,
            [In] int fContextReq,
            [In] int TargetDataRep,
            [In][Out] ref SecHandle phNewContext,
            [In][Out] ref SecBufferDesc pOutput,
            [Out] out uint pfContextAttr,
            [Out] out SECURITY_INTEGER ptsTimeStamp);


        /// <summary>
        /// Enables the server component of a transport application to establish a security context 
        /// between the server and a remote client. The remote client uses the InitializeSecurityContext 
        /// function to start the process of establishing a security context. 
        /// The server can require one or more reply tokens from the remote client to complete establishing
        /// the security context.
        /// </summary>
        /// <param name="phCredential">A handle to the credentials of the server. The server calls the AcquireCredentialsHandle (Negotiate) function with either the SECPKG_CRED_INBOUND or SECPKG_CRED_BOTH flag set to retrieve this handle.</param>
        /// <param name="phContext">A pointer to a CtxtHandle structure. On the first call to AcceptSecurityContext (Negotiate), this pointer is NULL. On subsequent calls, phContext is the handle to the partially formed context that was returned in the phNewContext parameter by the first call.</param>
        /// <param name="pInput">A pointer to a SecBufferDesc structure generated by a client call to InitializeSecurityContext (Negotiate) that contains the input buffer descriptor.</param>
        /// <param name="fContextReq">Bit flags that specify the attributes required by the server to establish the context.</param>
        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target. SECURITY_NATIVE_DREP or SECURITY_NETWORK_DREP</param>
        /// <param name="phNewContext">A pointer to a CtxtHandle structure.</param>
        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the output buffer descriptor. This buffer is sent to the client for input into additional calls to InitializeSecurityContext.</param>
        /// <param name="pfContextAttr">A pointer to a variable that receives a set of bit flags that indicate the attributes of the established context.</param>
        /// <param name="ptsTimeStamp">A pointer to a TimeStamp structure that receives the expiration time of the context.</param>
        /// <returns>Returns SEC_E_OK when the security context from the client is accepted.</returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int AcceptSecurityContext(
            [In] ref SecHandle phCredential,
            [In] IntPtr phContext,
            [In] ref SecBufferDesc pInput,
            [In] int fContextReq,
            [In] int TargetDataRep,
            [In][Out] ref SecHandle phNewContext,
            [In][Out] ref SecBufferDesc pOutput,
            [Out] out uint pfContextAttr,
            [Out] out SECURITY_INTEGER ptsTimeStamp);


        /// <summary>
        /// The CompleteAuthToken function completes an authentication token. This function is used 
        /// by protocols, such as DCE, that need to revise the security information after the transport 
        /// application has updated some message parameters. 
        /// </summary>
        /// <param name="phNewContext">A handle of the context that needs to be completed.</param>
        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains the buffer descriptor for the entire message.</param>
        /// <returns>If the function succeeds, the function returns SEC_E_OK. </returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int CompleteAuthToken(
            [In] ref SecHandle phNewContext,
            [In] ref SecBufferDesc pOutput
            );

        /// <summary>
        /// Acquires a handle to preexisting credentials of a security principal. This handle is required 
        /// by the InitializeSecurityContext and AcceptSecurityContext functions.
        /// </summary>
        /// <param name="pszPrincipal">A string that specifies the name of the principal whose credentials the handle will reference. A null string indicates that the process requires a handle to the credentials of the user under whose security context it is executing.</param>
        /// <param name="pszPackage">A string that specifies the name of the security package with which these credentials will be used. (Negotiate, Kerberos, NTLM)</param>
        /// <param name="fCredentialUse">A flag that indicates how these credentials will be used.</param>
        /// <param name="pvLogonID">A pointer to a locally unique identifier (LUID) that identifies the user</param>
        /// <param name="pAuthData">A pointer to package-specific data. This parameter can be NULL, which indicates that the default credentials for that package must be used.</param>
        /// <param name="pGetKeyFn">This parameter is not used and should be set to NULL</param>
        /// <param name="pvGetKeyArgument">This parameter is not used and should be set to NULL</param>
        /// <param name="phCredential">A pointer to a SECURITY_HANDLE structure to receive the credential handle.</param>
        /// <param name="ptsExpiry">A pointer to a TimeStamp structure that receives the time at which the returned credentials expire.</param>
        /// <returns>If the function succeeds, the function returns SEC_E_OK</returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int AcquireCredentialsHandle(
            [In] string pszPrincipal,
            [In] string pszPackage,
            [In] int fCredentialUse,
            [In] IntPtr pvLogonID,
            [In] IntPtr pAuthData,
            [In] int pGetKeyFn,
            [In] IntPtr pvGetKeyArgument,
            [Out] out SecHandle phCredential,
            [Out] out SECURITY_INTEGER ptsExpiry);

        /// <summary>
        /// Deletes the local data structures associated with the specified security context.
        /// </summary>
        /// <param name="phContext">Handle of the security context to delete</param>
        /// <returns>Function returns SEC_E_OK on success, SEC_E_INVALID_HANDLE on failure.</returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int DeleteSecurityContext([In] ref SecHandle phContext);

        /// <summary>
        /// Notifies the security system that the credentials are no longer needed.
        /// </summary>
        /// <param name="phCredential">A pointer to the credential handle obtained by using the AcquireCredentialsHandle function</param>
        /// <returns>Function returns SEC_E_OK on success, SEC_E_INVALID_HANDLE on failure.</returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int FreeCredentialsHandle([In] ref SecHandle phCredential);

        /// <summary>
        /// Initiates the client side, outbound security context from a credential handle. 
        /// </summary>
        /// <param name="phCredential">A handle to the credentials returned by AcquireCredentialsHandle.</param>
        /// <param name="phContext">A pointer to a CtxtHandle structure. On the first call to InitializeSecurityContext (Negotiate), this pointer is NULL.</param>
        /// <param name="pszTargetName">A pointer to a null-terminated string that indicates the service principal name (SPN) or the security context of the destination server.</param>
        /// <param name="fContextReq">Bit flags that indicate requests for the context.</param>
        /// <param name="Reserved1">This parameter is reserved and must be set to zero.</param>
        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target. SECURITY_NATIVE_DREP or SECURITY_NETWORK_DREP</param>
        /// <param name="SecBufferDesc">A pointer to a SecBufferDesc structure that contains pointers to the buffers supplied as input to the package. The pointer must be NULL on the first call to the function.</param>
        /// <param name="Reserved2">This parameter is reserved and must be set to zero.</param>
        /// <param name="phNewContext">A pointer to a CtxtHandle structure.</param>
        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains pointers to the SecBuffer structure that receives the output data.</param>
        /// <param name="pfContextAttr">A pointer to a variable to receive a set of bit flags that indicate the attributes of the established context.</param>
        /// <param name="ptsExpiry">A pointer to a TimeStamp structure that receives the expiration time of the context.</param>
        /// <returns>SEC_E_OK if the security context was successfully initialized.</returns>
        [DllImport("secur32.dll", SetLastError = true)]
        public static extern int InitializeSecurityContext(
            [In] ref SecHandle phCredential,
            [In] IntPtr phContext,
            [In] string pszTargetName,
            [In] int fContextReq,
            [In] int Reserved1,
            [In] int TargetDataRep,
            [In] IntPtr SecBufferDesc,
            [In] int Reserved2,
            [In][Out] ref SecHandle phNewContext,
            [In][Out] ref SecBufferDesc pOutput,
            [Out] out uint pfContextAttr,
            [Out] out SECURITY_INTEGER ptsExpiry);

        /// <summary>
        /// Initiates the client side, outbound security context from a credential handle. 
        /// </summary>
        /// <param name="phCredential">A handle to the credentials returned by AcquireCredentialsHandle.</param>
        /// <param name="phContext">A pointer to a CtxtHandle structure. On the first call to InitializeSecurityContext (Negotiate), this pointer is NULL.</param>
        /// <param name="pszTargetName">A pointer to a null-terminated string that indicates the service principal name (SPN) or the security context of the destination server.</param>
        /// <param name="fContextReq">Bit flags that indicate requests for the context.</param>
        /// <param name="Reserved1">This parameter is reserved and must be set to zero.</param>
        /// <param name="TargetDataRep">The data representation, such as byte ordering, on the target. SECURITY_NATIVE_DREP or SECURITY_NETWORK_DREP</param>
        /// <param name="SecBufferDesc">A pointer to a SecBufferDesc structure that contains pointers to the buffers supplied as input to the package. The pointer must be NULL on the first call to the function.</param>
        /// <param name="Reserved2">This parameter is reserved and must be set to zero.</param>
        /// <param name="phNewContext">A pointer to a CtxtHandle structure.</param>
        /// <param name="pOutput">A pointer to a SecBufferDesc structure that contains pointers to the SecBuffer structure that receives the output data.</param>
        /// <param name="pfContextAttr">A pointer to a variable to receive a set of bit flags that indicate the attributes of the established context.</param>
        /// <param name="ptsExpiry">A pointer to a TimeStamp structure that receives the expiration time of the context.</param>
        /// <returns>SEC_E_OK if the security context was successfully initialized.</returns>
        [DllImport("secur32.dll", SetLastError = true)]
        public static extern int InitializeSecurityContext(
            [In] ref SecHandle phCredential,
            [In] ref SecHandle phContext,
            [In] string pszTargetName,
            [In] int fContextReq,
            [In] int Reserved1,
            [In] int TargetDataRep,
            [In] ref SecBufferDesc SecBufferDesc,
            [In] int Reserved2,
            [In][Out] ref SecHandle phNewContext,
            [In][Out] ref SecBufferDesc pOutput,
            [Out] out uint pfContextAttr,
            [Out] out SECURITY_INTEGER ptsExpiry);

        /// <summary>
        /// Obtains the access token for a client security context and uses it directly.
        /// </summary>
        /// <param name="phContext">Handle of the context to query</param>
        /// <param name="phToken">Returned handle to the access token.</param>
        /// <returns>If the function succeeds, the function returns SEC_E_OK.</returns>
        [DllImport("secur32.dll", CharSet = CharSet.Auto)]
        public static extern int QuerySecurityContextToken(
            [In] ref SecHandle phContext, 
            [Out] out IntPtr phToken);
    }
}
