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