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