msxml3: Don't allocate new strings when returning namespace related data.
[wine] / dlls / secur32 / schannel.c
1 /* Copyright (C) 2005 Juan Lang
2  * Copyright 2008 Henri Verbeet
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  * This file implements the schannel provider, or, the SSL/TLS implementations.
19  */
20 #include "config.h"
21 #include "wine/port.h"
22
23 #include <stdarg.h>
24 #include <errno.h>
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winnls.h"
29 #include "sspi.h"
30 #include "schannel.h"
31 #include "secur32_priv.h"
32 #include "wine/debug.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
35
36 #if defined(SONAME_LIBGNUTLS) || defined (HAVE_SECURITY_SECURITY_H)
37
38 #define SCHAN_INVALID_HANDLE ~0UL
39
40 enum schan_handle_type
41 {
42     SCHAN_HANDLE_CRED,
43     SCHAN_HANDLE_CTX,
44     SCHAN_HANDLE_FREE
45 };
46
47 struct schan_handle
48 {
49     void *object;
50     enum schan_handle_type type;
51 };
52
53 struct schan_credentials
54 {
55     ULONG credential_use;
56     schan_imp_certificate_credentials credentials;
57 };
58
59 struct schan_context
60 {
61     schan_imp_session session;
62     ULONG req_ctx_attr;
63 };
64
65 static struct schan_handle *schan_handle_table;
66 static struct schan_handle *schan_free_handles;
67 static SIZE_T schan_handle_table_size;
68 static SIZE_T schan_handle_count;
69
70 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
71 {
72     struct schan_handle *handle;
73
74     if (schan_free_handles)
75     {
76         DWORD index = schan_free_handles - schan_handle_table;
77         /* Use a free handle */
78         handle = schan_free_handles;
79         if (handle->type != SCHAN_HANDLE_FREE)
80         {
81             ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
82             return SCHAN_INVALID_HANDLE;
83         }
84         schan_free_handles = handle->object;
85         handle->object = object;
86         handle->type = type;
87
88         return index;
89     }
90     if (!(schan_handle_count < schan_handle_table_size))
91     {
92         /* Grow the table */
93         SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
94         struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
95         if (!new_table)
96         {
97             ERR("Failed to grow the handle table\n");
98             return SCHAN_INVALID_HANDLE;
99         }
100         schan_handle_table = new_table;
101         schan_handle_table_size = new_size;
102     }
103
104     handle = &schan_handle_table[schan_handle_count++];
105     handle->object = object;
106     handle->type = type;
107
108     return handle - schan_handle_table;
109 }
110
111 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
112 {
113     struct schan_handle *handle;
114     void *object;
115
116     if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
117     if (handle_idx >= schan_handle_count) return NULL;
118     handle = &schan_handle_table[handle_idx];
119     if (handle->type != type)
120     {
121         ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
122         return NULL;
123     }
124
125     object = handle->object;
126     handle->object = schan_free_handles;
127     handle->type = SCHAN_HANDLE_FREE;
128     schan_free_handles = handle;
129
130     return object;
131 }
132
133 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
134 {
135     struct schan_handle *handle;
136
137     if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
138     if (handle_idx >= schan_handle_count) return NULL;
139     handle = &schan_handle_table[handle_idx];
140     if (handle->type != type)
141     {
142         ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
143         return NULL;
144     }
145
146     return handle->object;
147 }
148
149 static SECURITY_STATUS schan_QueryCredentialsAttributes(
150  PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
151 {
152     SECURITY_STATUS ret;
153
154     switch (ulAttribute)
155     {
156     case SECPKG_ATTR_SUPPORTED_ALGS:
157         if (pBuffer)
158         {
159             /* FIXME: get from CryptoAPI */
160             FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
161             ret = SEC_E_UNSUPPORTED_FUNCTION;
162         }
163         else
164             ret = SEC_E_INTERNAL_ERROR;
165         break;
166     case SECPKG_ATTR_CIPHER_STRENGTHS:
167         if (pBuffer)
168         {
169             SecPkgCred_CipherStrengths *r = pBuffer;
170
171             /* FIXME: get from CryptoAPI */
172             FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
173             r->dwMinimumCipherStrength = 40;
174             r->dwMaximumCipherStrength = 168;
175             ret = SEC_E_OK;
176         }
177         else
178             ret = SEC_E_INTERNAL_ERROR;
179         break;
180     case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
181         if (pBuffer)
182         {
183             /* FIXME: get from OpenSSL? */
184             FIXME("SECPKG_ATTR_SUPPORTED_PROTOCOLS: stub\n");
185             ret = SEC_E_UNSUPPORTED_FUNCTION;
186         }
187         else
188             ret = SEC_E_INTERNAL_ERROR;
189         break;
190     default:
191         ret = SEC_E_UNSUPPORTED_FUNCTION;
192     }
193     return ret;
194 }
195
196 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
197  PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
198 {
199     SECURITY_STATUS ret;
200
201     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
202
203     switch (ulAttribute)
204     {
205     case SECPKG_CRED_ATTR_NAMES:
206         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
207         ret = SEC_E_UNSUPPORTED_FUNCTION;
208         break;
209     default:
210         ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
211          pBuffer);
212     }
213     return ret;
214 }
215
216 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
217  PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
218 {
219     SECURITY_STATUS ret;
220
221     TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
222
223     switch (ulAttribute)
224     {
225     case SECPKG_CRED_ATTR_NAMES:
226         FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
227         ret = SEC_E_UNSUPPORTED_FUNCTION;
228         break;
229     default:
230         ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
231          pBuffer);
232     }
233     return ret;
234 }
235
236 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
237 {
238     SECURITY_STATUS st;
239     DWORD i;
240
241     TRACE("dwVersion = %d\n", schanCred->dwVersion);
242     TRACE("cCreds = %d\n", schanCred->cCreds);
243     TRACE("hRootStore = %p\n", schanCred->hRootStore);
244     TRACE("cMappers = %d\n", schanCred->cMappers);
245     TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
246     for (i = 0; i < schanCred->cSupportedAlgs; i++)
247         TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
248     TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
249     TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
250     TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
251     TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
252     TRACE("dwFlags = %08x\n", schanCred->dwFlags);
253     TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
254
255     switch (schanCred->dwVersion)
256     {
257     case SCH_CRED_V3:
258     case SCHANNEL_CRED_VERSION:
259         break;
260     default:
261         return SEC_E_INTERNAL_ERROR;
262     }
263
264     if (schanCred->cCreds == 0)
265         st = SEC_E_NO_CREDENTIALS;
266     else if (schanCred->cCreds > 1)
267         st = SEC_E_UNKNOWN_CREDENTIALS;
268     else
269     {
270         DWORD keySpec;
271         HCRYPTPROV csp;
272         BOOL ret, freeCSP;
273
274         ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
275          0, /* FIXME: what flags to use? */ NULL,
276          &csp, &keySpec, &freeCSP);
277         if (ret)
278         {
279             st = SEC_E_OK;
280             if (freeCSP)
281                 CryptReleaseContext(csp, 0);
282         }
283         else
284             st = SEC_E_UNKNOWN_CREDENTIALS;
285     }
286     return st;
287 }
288
289 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
290  PCredHandle phCredential, PTimeStamp ptsExpiry)
291 {
292     struct schan_credentials *creds;
293     SECURITY_STATUS st = SEC_E_OK;
294
295     TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
296
297     if (schanCred)
298     {
299         st = schan_CheckCreds(schanCred);
300         if (st == SEC_E_NO_CREDENTIALS)
301             st = SEC_E_OK;
302     }
303
304     /* For now, the only thing I'm interested in is the direction of the
305      * connection, so just store it.
306      */
307     if (st == SEC_E_OK)
308     {
309         ULONG_PTR handle;
310
311         creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
312         if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
313
314         handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
315         if (handle == SCHAN_INVALID_HANDLE) goto fail;
316
317         creds->credential_use = SECPKG_CRED_OUTBOUND;
318         if (!schan_imp_allocate_certificate_credentials(&creds->credentials))
319         {
320             schan_free_handle(handle, SCHAN_HANDLE_CRED);
321             goto fail;
322         }
323
324         phCredential->dwLower = handle;
325         phCredential->dwUpper = 0;
326
327         /* Outbound credentials have no expiry */
328         if (ptsExpiry)
329         {
330             ptsExpiry->LowPart = 0;
331             ptsExpiry->HighPart = 0;
332         }
333     }
334     return st;
335
336 fail:
337     HeapFree(GetProcessHeap(), 0, creds);
338     return SEC_E_INTERNAL_ERROR;
339 }
340
341 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
342  PCredHandle phCredential, PTimeStamp ptsExpiry)
343 {
344     SECURITY_STATUS st;
345
346     TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
347
348     if (!schanCred) return SEC_E_NO_CREDENTIALS;
349
350     st = schan_CheckCreds(schanCred);
351     if (st == SEC_E_OK)
352     {
353         ULONG_PTR handle;
354         struct schan_credentials *creds;
355
356         creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
357         if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
358         creds->credential_use = SECPKG_CRED_INBOUND;
359
360         handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
361         if (handle == SCHAN_INVALID_HANDLE)
362         {
363             HeapFree(GetProcessHeap(), 0, creds);
364             return SEC_E_INTERNAL_ERROR;
365         }
366
367         phCredential->dwLower = handle;
368         phCredential->dwUpper = 0;
369
370         /* FIXME: get expiry from cert */
371     }
372     return st;
373 }
374
375 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
376  const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
377 {
378     SECURITY_STATUS ret;
379
380     if (fCredentialUse == SECPKG_CRED_OUTBOUND)
381         ret = schan_AcquireClientCredentials(schanCred, phCredential,
382          ptsExpiry);
383     else
384         ret = schan_AcquireServerCredentials(schanCred, phCredential,
385          ptsExpiry);
386     return ret;
387 }
388
389 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
390  SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
391  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
392  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
393 {
394     TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
395      debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
396      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
397     return schan_AcquireCredentialsHandle(fCredentialUse,
398      pAuthData, phCredential, ptsExpiry);
399 }
400
401 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
402  SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
403  PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
404  PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
405 {
406     TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
407      debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
408      pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
409     return schan_AcquireCredentialsHandle(fCredentialUse,
410      pAuthData, phCredential, ptsExpiry);
411 }
412
413 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
414  PCredHandle phCredential)
415 {
416     struct schan_credentials *creds;
417
418     TRACE("phCredential %p\n", phCredential);
419
420     if (!phCredential) return SEC_E_INVALID_HANDLE;
421
422     creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
423     if (!creds) return SEC_E_INVALID_HANDLE;
424
425     if (creds->credential_use == SECPKG_CRED_OUTBOUND)
426         schan_imp_free_certificate_credentials(creds->credentials);
427     HeapFree(GetProcessHeap(), 0, creds);
428
429     return SEC_E_OK;
430 }
431
432 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
433         int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
434 {
435     s->offset = 0;
436     s->limit = ~0UL;
437     s->desc = desc;
438     s->current_buffer_idx = -1;
439     s->allow_buffer_resize = FALSE;
440     s->get_next_buffer = get_next_buffer;
441 }
442
443 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
444 {
445     unsigned int i;
446     PSecBuffer buffer;
447
448     for (i = start_idx; i < desc->cBuffers; ++i)
449     {
450         buffer = &desc->pBuffers[i];
451         if (buffer->BufferType == buffer_type) return i;
452     }
453
454     return -1;
455 }
456
457 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
458 {
459     SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
460     SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
461     void *new_data;
462
463     if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
464
465     while (new_size < min_size) new_size *= 2;
466
467     if (b->pvBuffer)
468         new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
469     else
470         new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
471
472     if (!new_data)
473     {
474         TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
475         return;
476     }
477
478     b->cbBuffer = new_size;
479     b->pvBuffer = new_data;
480 }
481
482 char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
483 {
484     SIZE_T max_count;
485     PSecBuffer buffer;
486
487     if (!s->desc)
488     {
489         TRACE("No desc\n");
490         return NULL;
491     }
492
493     if (s->current_buffer_idx == -1)
494     {
495         /* Initial buffer */
496         int buffer_idx = s->get_next_buffer(t, s);
497         if (buffer_idx == -1)
498         {
499             TRACE("No next buffer\n");
500             return NULL;
501         }
502         s->current_buffer_idx = buffer_idx;
503     }
504
505     buffer = &s->desc->pBuffers[s->current_buffer_idx];
506     TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
507
508     schan_resize_current_buffer(s, s->offset + *count);
509     max_count = buffer->cbBuffer - s->offset;
510     if (s->limit != ~0UL && s->limit < max_count)
511         max_count = s->limit;
512     if (!max_count)
513     {
514         int buffer_idx;
515
516         s->allow_buffer_resize = FALSE;
517         buffer_idx = s->get_next_buffer(t, s);
518         if (buffer_idx == -1)
519         {
520             TRACE("No next buffer\n");
521             return NULL;
522         }
523         s->current_buffer_idx = buffer_idx;
524         s->offset = 0;
525         return schan_get_buffer(t, s, count);
526     }
527
528     if (*count > max_count)
529         *count = max_count;
530     if (s->limit != ~0UL)
531         s->limit -= *count;
532
533     return (char *)buffer->pvBuffer + s->offset;
534 }
535
536 /* schan_pull
537  *      Read data from the transport input buffer.
538  *
539  * t - The session transport object.
540  * buff - The buffer into which to store the read data.  Must be at least
541  *        *buff_len bytes in length.
542  * buff_len - On input, *buff_len is the desired length to read.  On successful
543  *            return, *buff_len is the number of bytes actually read.
544  *
545  * Returns:
546  *  0 on success, in which case:
547  *      *buff_len == 0 indicates end of file.
548  *      *buff_len > 0 indicates that some data was read.  May be less than
549  *          what was requested, in which case the caller should call again if/
550  *          when they want more.
551  *  EAGAIN when no data could be read without blocking
552  *  another errno-style error value on failure
553  *
554  */
555 int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
556 {
557     char *b;
558     SIZE_T local_len = *buff_len;
559
560     TRACE("Pull %lu bytes\n", local_len);
561
562     *buff_len = 0;
563
564     b = schan_get_buffer(t, &t->in, &local_len);
565     if (!b)
566         return EAGAIN;
567
568     memcpy(buff, b, local_len);
569     t->in.offset += local_len;
570
571     TRACE("Read %lu bytes\n", local_len);
572
573     *buff_len = local_len;
574     return 0;
575 }
576
577 /* schan_push
578  *      Write data to the transport output buffer.
579  *
580  * t - The session transport object.
581  * buff - The buffer of data to write.  Must be at least *buff_len bytes in length.
582  * buff_len - On input, *buff_len is the desired length to write.  On successful
583  *            return, *buff_len is the number of bytes actually written.
584  *
585  * Returns:
586  *  0 on success
587  *      *buff_len will be > 0 indicating how much data was written.  May be less
588  *          than what was requested, in which case the caller should call again
589             if/when they want to write more.
590  *  EAGAIN when no data could be written without blocking
591  *  another errno-style error value on failure
592  *
593  */
594 int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
595 {
596     char *b;
597     SIZE_T local_len = *buff_len;
598
599     TRACE("Push %lu bytes\n", local_len);
600
601     *buff_len = 0;
602
603     b = schan_get_buffer(t, &t->out, &local_len);
604     if (!b)
605         return EAGAIN;
606
607     memcpy(b, buff, local_len);
608     t->out.offset += local_len;
609
610     TRACE("Wrote %lu bytes\n", local_len);
611
612     *buff_len = local_len;
613     return 0;
614 }
615
616 schan_imp_session schan_session_for_transport(struct schan_transport* t)
617 {
618     return t->ctx->session;
619 }
620
621 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
622 {
623     if (s->current_buffer_idx == -1)
624     {
625         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
626         if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
627         {
628             if (idx == -1)
629             {
630                 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
631                 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
632             }
633             if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
634             {
635                 s->desc->pBuffers[idx].cbBuffer = 0;
636                 s->allow_buffer_resize = TRUE;
637             }
638         }
639         return idx;
640     }
641
642     return -1;
643 }
644
645 static void dump_buffer_desc(SecBufferDesc *desc)
646 {
647     unsigned int i;
648
649     if (!desc) return;
650     TRACE("Buffer desc %p:\n", desc);
651     for (i = 0; i < desc->cBuffers; ++i)
652     {
653         SecBuffer *b = &desc->pBuffers[i];
654         TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
655     }
656 }
657
658 /***********************************************************************
659  *              InitializeSecurityContextW
660  */
661 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
662  PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
663  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
664  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
665  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
666 {
667     struct schan_context *ctx;
668     struct schan_buffers *out_buffers;
669     struct schan_credentials *cred;
670     struct schan_transport transport;
671     SECURITY_STATUS ret;
672
673     TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
674      debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
675      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
676
677     dump_buffer_desc(pInput);
678     dump_buffer_desc(pOutput);
679
680     if (!phContext)
681     {
682         ULONG_PTR handle;
683
684         if (!phCredential) return SEC_E_INVALID_HANDLE;
685
686         cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
687         if (!cred) return SEC_E_INVALID_HANDLE;
688
689         if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
690         {
691             WARN("Invalid credential use %#x\n", cred->credential_use);
692             return SEC_E_INVALID_HANDLE;
693         }
694
695         ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
696         if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
697
698         handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
699         if (handle == SCHAN_INVALID_HANDLE)
700         {
701             HeapFree(GetProcessHeap(), 0, ctx);
702             return SEC_E_INTERNAL_ERROR;
703         }
704
705         if (!schan_imp_create_session(&ctx->session, FALSE, cred->credentials))
706         {
707             schan_free_handle(handle, SCHAN_HANDLE_CTX);
708             HeapFree(GetProcessHeap(), 0, ctx);
709             return SEC_E_INTERNAL_ERROR;
710         }
711
712         phNewContext->dwLower = handle;
713         phNewContext->dwUpper = 0;
714     }
715     else
716     {
717         ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
718     }
719
720     ctx->req_ctx_attr = fContextReq;
721
722     transport.ctx = ctx;
723     init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
724     init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
725     schan_imp_set_session_transport(ctx->session, &transport);
726
727     /* Perform the TLS handshake */
728     ret = schan_imp_handshake(ctx->session);
729
730     if(transport.in.offset && transport.in.offset != pInput->pBuffers[0].cbBuffer) {
731         if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
732             return SEC_E_INVALID_TOKEN;
733
734         pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
735         pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-transport.in.offset;
736     }
737
738     out_buffers = &transport.out;
739     if (out_buffers->current_buffer_idx != -1)
740     {
741         SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
742         buffer->cbBuffer = out_buffers->offset;
743     }
744
745     *pfContextAttr = 0;
746     if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
747         *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
748
749     return ret;
750 }
751
752 /***********************************************************************
753  *              InitializeSecurityContextA
754  */
755 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
756  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
757  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
758  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
759  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
760 {
761     SECURITY_STATUS ret;
762     SEC_WCHAR *target_name = NULL;
763
764     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
765      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
766      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
767
768     if (pszTargetName)
769     {
770         INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
771         target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
772         MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
773     }
774
775     ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
776             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
777             phNewContext, pOutput, pfContextAttr, ptsExpiry);
778
779     HeapFree(GetProcessHeap(), 0, target_name);
780
781     return ret;
782 }
783
784 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
785         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
786 {
787     struct schan_context *ctx;
788
789     TRACE("context_handle %p, attribute %#x, buffer %p\n",
790             context_handle, attribute, buffer);
791
792     if (!context_handle) return SEC_E_INVALID_HANDLE;
793     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
794
795     switch(attribute)
796     {
797         case SECPKG_ATTR_STREAM_SIZES:
798         {
799             SecPkgContext_ConnectionInfo info;
800             SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &info);
801             if (status == SEC_E_OK)
802             {
803                 SecPkgContext_StreamSizes *stream_sizes = buffer;
804                 SIZE_T mac_size = info.dwHashStrength;
805                 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
806                 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
807
808                 TRACE("Using %lu mac bytes, message size %u, block size %u\n",
809                         mac_size, message_size, block_size);
810
811                 /* These are defined by the TLS RFC */
812                 stream_sizes->cbHeader = 5;
813                 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
814                 stream_sizes->cbMaximumMessage = message_size;
815                 stream_sizes->cbBuffers = 4;
816                 stream_sizes->cbBlockSize = block_size;
817             }
818
819             return status;
820         }
821         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
822         {
823             PCCERT_CONTEXT *cert = buffer;
824             return schan_imp_get_session_peer_certificate(ctx->session, cert);
825         }
826         case SECPKG_ATTR_CONNECTION_INFO:
827         {
828             SecPkgContext_ConnectionInfo *info = buffer;
829             return schan_imp_get_connection_info(ctx->session, info);
830         }
831
832         default:
833             FIXME("Unhandled attribute %#x\n", attribute);
834             return SEC_E_UNSUPPORTED_FUNCTION;
835     }
836 }
837
838 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
839         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
840 {
841     TRACE("context_handle %p, attribute %#x, buffer %p\n",
842             context_handle, attribute, buffer);
843
844     switch(attribute)
845     {
846         case SECPKG_ATTR_STREAM_SIZES:
847             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
848         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
849             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
850         case SECPKG_ATTR_CONNECTION_INFO:
851             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
852
853         default:
854             FIXME("Unhandled attribute %#x\n", attribute);
855             return SEC_E_UNSUPPORTED_FUNCTION;
856     }
857 }
858
859 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
860 {
861     SecBuffer *b;
862
863     if (s->current_buffer_idx == -1)
864         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
865
866     b = &s->desc->pBuffers[s->current_buffer_idx];
867
868     if (b->BufferType == SECBUFFER_STREAM_HEADER)
869         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
870
871     if (b->BufferType == SECBUFFER_DATA)
872         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
873
874     return -1;
875 }
876
877 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
878 {
879     SecBuffer *b;
880
881     if (s->current_buffer_idx == -1)
882         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
883
884     b = &s->desc->pBuffers[s->current_buffer_idx];
885
886     if (b->BufferType == SECBUFFER_TOKEN)
887     {
888         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
889         if (idx != s->current_buffer_idx) return -1;
890         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
891     }
892
893     if (b->BufferType == SECBUFFER_DATA)
894     {
895         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
896         if (idx != -1)
897             idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
898         return idx;
899     }
900
901     return -1;
902 }
903
904 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
905         ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
906 {
907     struct schan_transport transport;
908     struct schan_context *ctx;
909     struct schan_buffers *b;
910     SECURITY_STATUS status;
911     SecBuffer *buffer;
912     SIZE_T data_size;
913     SIZE_T length;
914     char *data;
915     int idx;
916
917     TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
918             context_handle, quality, message, message_seq_no);
919
920     if (!context_handle) return SEC_E_INVALID_HANDLE;
921     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
922
923     dump_buffer_desc(message);
924
925     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
926     if (idx == -1)
927     {
928         WARN("No data buffer passed\n");
929         return SEC_E_INTERNAL_ERROR;
930     }
931     buffer = &message->pBuffers[idx];
932
933     data_size = buffer->cbBuffer;
934     data = HeapAlloc(GetProcessHeap(), 0, data_size);
935     memcpy(data, buffer->pvBuffer, data_size);
936
937     transport.ctx = ctx;
938     init_schan_buffers(&transport.in, NULL, NULL);
939     if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
940         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
941     else
942         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
943     schan_imp_set_session_transport(ctx->session, &transport);
944
945     length = data_size;
946     status = schan_imp_send(ctx->session, data, &length);
947
948     TRACE("Sent %ld bytes.\n", length);
949
950     if (length != data_size)
951         status = SEC_E_INTERNAL_ERROR;
952
953     b = &transport.out;
954     b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
955     HeapFree(GetProcessHeap(), 0, data);
956
957     TRACE("Returning %#x.\n", status);
958
959     return status;
960 }
961
962 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
963 {
964     if (s->current_buffer_idx == -1)
965         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
966
967     return -1;
968 }
969
970 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
971 {
972     int data_idx = -1;
973     unsigned int empty_count = 0;
974     unsigned int i;
975
976     if (message->cBuffers < 4)
977     {
978         WARN("Less than four buffers passed\n");
979         return -1;
980     }
981
982     for (i = 0; i < message->cBuffers; ++i)
983     {
984         SecBuffer *b = &message->pBuffers[i];
985         if (b->BufferType == SECBUFFER_DATA)
986         {
987             if (data_idx != -1)
988             {
989                 WARN("More than one data buffer passed\n");
990                 return -1;
991             }
992             data_idx = i;
993         }
994         else if (b->BufferType == SECBUFFER_EMPTY)
995             ++empty_count;
996     }
997
998     if (data_idx == -1)
999     {
1000         WARN("No data buffer passed\n");
1001         return -1;
1002     }
1003
1004     if (empty_count < 3)
1005     {
1006         WARN("Less than three empty buffers passed\n");
1007         return -1;
1008     }
1009
1010     return data_idx;
1011 }
1012
1013 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1014 {
1015     int idx;
1016     SecBuffer *buffer;
1017
1018     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1019     buffer = &message->pBuffers[idx];
1020
1021     buffer->BufferType = buffer_type;
1022     buffer->pvBuffer = data;
1023     buffer->cbBuffer = size;
1024 }
1025
1026 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1027         PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1028 {
1029     struct schan_transport transport;
1030     struct schan_context *ctx;
1031     SecBuffer *buffer;
1032     SIZE_T data_size;
1033     char *data;
1034     unsigned expected_size;
1035     SSIZE_T received = 0;
1036     int idx;
1037     unsigned char *buf_ptr;
1038
1039     TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1040             context_handle, message, message_seq_no, quality);
1041
1042     if (!context_handle) return SEC_E_INVALID_HANDLE;
1043     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1044
1045     dump_buffer_desc(message);
1046
1047     idx = schan_validate_decrypt_buffer_desc(message);
1048     if (idx == -1)
1049         return SEC_E_INVALID_TOKEN;
1050     buffer = &message->pBuffers[idx];
1051     buf_ptr = buffer->pvBuffer;
1052
1053     expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1054     if(buffer->cbBuffer < expected_size)
1055     {
1056         TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1057         buffer->BufferType = SECBUFFER_MISSING;
1058         buffer->cbBuffer = expected_size - buffer->cbBuffer;
1059
1060         /* This is a bit weird, but windows does it too */
1061         idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1062         buffer = &message->pBuffers[idx];
1063         buffer->BufferType = SECBUFFER_MISSING;
1064         buffer->cbBuffer = expected_size - buffer->cbBuffer;
1065
1066         TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1067         return SEC_E_INCOMPLETE_MESSAGE;
1068     }
1069
1070     data_size = buffer->cbBuffer;
1071     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1072
1073     transport.ctx = ctx;
1074     init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1075     transport.in.limit = expected_size;
1076     init_schan_buffers(&transport.out, NULL, NULL);
1077     schan_imp_set_session_transport(ctx->session, &transport);
1078
1079     while (received < data_size)
1080     {
1081         SIZE_T length = data_size - received;
1082         SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1083         if (status == SEC_I_CONTINUE_NEEDED)
1084         {
1085             if (!received)
1086             {
1087                 HeapFree(GetProcessHeap(), 0, data);
1088                 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1089                 return SEC_E_INCOMPLETE_MESSAGE;
1090             }
1091             break;
1092         }
1093         else if (status != SEC_E_OK)
1094         {
1095             HeapFree(GetProcessHeap(), 0, data);
1096             ERR("Returning %d\n", status);
1097             return status;
1098         }
1099         else if (!length)
1100             break;
1101
1102         received += length;
1103     }
1104
1105     TRACE("Received %ld bytes\n", received);
1106
1107     memcpy(buf_ptr + 5, data, received);
1108     HeapFree(GetProcessHeap(), 0, data);
1109
1110     schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1111         buf_ptr + 5, received);
1112
1113     schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1114         buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1115
1116     if(buffer->cbBuffer > expected_size)
1117         schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1118             buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1119
1120     buffer->BufferType = SECBUFFER_STREAM_HEADER;
1121     buffer->cbBuffer = 5;
1122
1123     return SEC_E_OK;
1124 }
1125
1126 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1127 {
1128     struct schan_context *ctx;
1129
1130     TRACE("context_handle %p\n", context_handle);
1131
1132     if (!context_handle) return SEC_E_INVALID_HANDLE;
1133
1134     ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1135     if (!ctx) return SEC_E_INVALID_HANDLE;
1136
1137     schan_imp_dispose_session(ctx->session);
1138     HeapFree(GetProcessHeap(), 0, ctx);
1139
1140     return SEC_E_OK;
1141 }
1142
1143 static const SecurityFunctionTableA schanTableA = {
1144     1,
1145     NULL, /* EnumerateSecurityPackagesA */
1146     schan_QueryCredentialsAttributesA,
1147     schan_AcquireCredentialsHandleA,
1148     schan_FreeCredentialsHandle,
1149     NULL, /* Reserved2 */
1150     schan_InitializeSecurityContextA, 
1151     NULL, /* AcceptSecurityContext */
1152     NULL, /* CompleteAuthToken */
1153     schan_DeleteSecurityContext,
1154     NULL, /* ApplyControlToken */
1155     schan_QueryContextAttributesA,
1156     NULL, /* ImpersonateSecurityContext */
1157     NULL, /* RevertSecurityContext */
1158     NULL, /* MakeSignature */
1159     NULL, /* VerifySignature */
1160     FreeContextBuffer,
1161     NULL, /* QuerySecurityPackageInfoA */
1162     NULL, /* Reserved3 */
1163     NULL, /* Reserved4 */
1164     NULL, /* ExportSecurityContext */
1165     NULL, /* ImportSecurityContextA */
1166     NULL, /* AddCredentialsA */
1167     NULL, /* Reserved8 */
1168     NULL, /* QuerySecurityContextToken */
1169     schan_EncryptMessage,
1170     schan_DecryptMessage,
1171     NULL, /* SetContextAttributesA */
1172 };
1173
1174 static const SecurityFunctionTableW schanTableW = {
1175     1,
1176     NULL, /* EnumerateSecurityPackagesW */
1177     schan_QueryCredentialsAttributesW,
1178     schan_AcquireCredentialsHandleW,
1179     schan_FreeCredentialsHandle,
1180     NULL, /* Reserved2 */
1181     schan_InitializeSecurityContextW, 
1182     NULL, /* AcceptSecurityContext */
1183     NULL, /* CompleteAuthToken */
1184     schan_DeleteSecurityContext,
1185     NULL, /* ApplyControlToken */
1186     schan_QueryContextAttributesW,
1187     NULL, /* ImpersonateSecurityContext */
1188     NULL, /* RevertSecurityContext */
1189     NULL, /* MakeSignature */
1190     NULL, /* VerifySignature */
1191     FreeContextBuffer,
1192     NULL, /* QuerySecurityPackageInfoW */
1193     NULL, /* Reserved3 */
1194     NULL, /* Reserved4 */
1195     NULL, /* ExportSecurityContext */
1196     NULL, /* ImportSecurityContextW */
1197     NULL, /* AddCredentialsW */
1198     NULL, /* Reserved8 */
1199     NULL, /* QuerySecurityContextToken */
1200     schan_EncryptMessage,
1201     schan_DecryptMessage,
1202     NULL, /* SetContextAttributesW */
1203 };
1204
1205 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1206  'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1207 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1208
1209 void SECUR32_initSchannelSP(void)
1210 {
1211     /* This is what Windows reports.  This shouldn't break any applications
1212      * even though the functions are missing, because the wrapper will
1213      * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1214      */
1215     static const LONG caps =
1216         SECPKG_FLAG_INTEGRITY |
1217         SECPKG_FLAG_PRIVACY |
1218         SECPKG_FLAG_CONNECTION |
1219         SECPKG_FLAG_MULTI_REQUIRED |
1220         SECPKG_FLAG_EXTENDED_ERROR |
1221         SECPKG_FLAG_IMPERSONATION |
1222         SECPKG_FLAG_ACCEPT_WIN32_NAME |
1223         SECPKG_FLAG_STREAM;
1224     static const short version = 1;
1225     static const LONG maxToken = 16384;
1226     SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1227               *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1228     const SecPkgInfoW info[] = {
1229         { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1230         { caps, version, UNISP_RPC_ID, maxToken, schannel,
1231             (SEC_WCHAR *)schannelComment },
1232     };
1233     SecureProvider *provider;
1234
1235     if (!schan_imp_init())
1236         return;
1237
1238     schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1239     if (!schan_handle_table)
1240     {
1241         ERR("Failed to allocate schannel handle table.\n");
1242         goto fail;
1243     }
1244     schan_handle_table_size = 64;
1245
1246     provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1247     if (!provider)
1248     {
1249         ERR("Failed to add schannel provider.\n");
1250         goto fail;
1251     }
1252
1253     SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1254
1255     return;
1256
1257 fail:
1258     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1259     schan_handle_table = NULL;
1260     schan_imp_deinit();
1261     return;
1262 }
1263
1264 void SECUR32_deinitSchannelSP(void)
1265 {
1266     SIZE_T i = schan_handle_count;
1267
1268     if (!schan_handle_table) return;
1269
1270     /* deinitialized sessions first because a pointer to the credentials
1271      * may be stored for the session. */
1272     while (i--)
1273     {
1274         if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1275         {
1276             struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1277             schan_imp_dispose_session(ctx->session);
1278             HeapFree(GetProcessHeap(), 0, ctx);
1279         }
1280     }
1281     i = schan_handle_count;
1282     while (i--)
1283     {
1284         if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1285         {
1286             struct schan_credentials *cred;
1287             cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1288             schan_imp_free_certificate_credentials(cred->credentials);
1289             HeapFree(GetProcessHeap(), 0, cred);
1290         }
1291     }
1292     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1293     schan_imp_deinit();
1294 }
1295
1296 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1297
1298 void SECUR32_initSchannelSP(void)
1299 {
1300     ERR("TLS library not found, SSL connections will fail\n");
1301 }
1302
1303 void SECUR32_deinitSchannelSP(void) {}
1304
1305 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */