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