gdiplus: Use WIC to decode PNG files.
[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     const SecBufferDesc *desc;
109     int current_buffer_idx;
110     BOOL allow_buffer_resize;
111     int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *);
112 };
113
114 struct schan_transport
115 {
116     struct schan_context *ctx;
117     struct schan_buffers in;
118     struct schan_buffers out;
119 };
120
121 static struct schan_handle *schan_handle_table;
122 static struct schan_handle *schan_free_handles;
123 static SIZE_T schan_handle_table_size;
124 static SIZE_T schan_handle_count;
125
126 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
127 {
128     struct schan_handle *handle;
129
130     if (schan_free_handles)
131     {
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", (handle-schan_handle_table), 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 handle - schan_handle_table;
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->desc = desc;
495     s->current_buffer_idx = -1;
496     s->allow_buffer_resize = FALSE;
497     s->get_next_buffer = get_next_buffer;
498 }
499
500 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
501 {
502     unsigned int i;
503     PSecBuffer buffer;
504
505     for (i = start_idx; i < desc->cBuffers; ++i)
506     {
507         buffer = &desc->pBuffers[i];
508         if (buffer->BufferType == buffer_type) return i;
509     }
510
511     return -1;
512 }
513
514 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
515 {
516     SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
517     SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
518     void *new_data;
519
520     if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
521
522     while (new_size < min_size) new_size *= 2;
523
524     if (b->pvBuffer)
525         new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
526     else
527         new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
528
529     if (!new_data)
530     {
531         TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
532         return;
533     }
534
535     b->cbBuffer = new_size;
536     b->pvBuffer = new_data;
537 }
538
539 static char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, size_t *count)
540 {
541     SIZE_T max_count;
542     PSecBuffer buffer;
543
544     if (!s->desc)
545     {
546         TRACE("No desc\n");
547         return NULL;
548     }
549
550     if (s->current_buffer_idx == -1)
551     {
552         /* Initial buffer */
553         int buffer_idx = s->get_next_buffer(t, s);
554         if (buffer_idx == -1)
555         {
556             TRACE("No next buffer\n");
557             return NULL;
558         }
559         s->current_buffer_idx = buffer_idx;
560     }
561
562     buffer = &s->desc->pBuffers[s->current_buffer_idx];
563     TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
564
565     schan_resize_current_buffer(s, s->offset + *count);
566     max_count = buffer->cbBuffer - s->offset;
567     if (!max_count)
568     {
569         int buffer_idx;
570
571         s->allow_buffer_resize = FALSE;
572         buffer_idx = s->get_next_buffer(t, s);
573         if (buffer_idx == -1)
574         {
575             TRACE("No next buffer\n");
576             return NULL;
577         }
578         s->current_buffer_idx = buffer_idx;
579         s->offset = 0;
580         return schan_get_buffer(t, s, count);
581     }
582
583     if (*count > max_count) *count = max_count;
584     return (char *)buffer->pvBuffer + s->offset;
585 }
586
587 static ssize_t schan_pull(gnutls_transport_ptr_t transport, void *buff, size_t buff_len)
588 {
589     struct schan_transport *t = transport;
590     char *b;
591
592     TRACE("Pull %zu bytes\n", buff_len);
593
594     b = schan_get_buffer(t, &t->in, &buff_len);
595     if (!b)
596     {
597         pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
598         return -1;
599     }
600
601     memcpy(buff, b, buff_len);
602     t->in.offset += buff_len;
603
604     TRACE("Read %zu bytes\n", buff_len);
605
606     return buff_len;
607 }
608
609 static ssize_t schan_push(gnutls_transport_ptr_t transport, const void *buff, size_t buff_len)
610 {
611     struct schan_transport *t = transport;
612     char *b;
613
614     TRACE("Push %zu bytes\n", buff_len);
615
616     b = schan_get_buffer(t, &t->out, &buff_len);
617     if (!b)
618     {
619         pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
620         return -1;
621     }
622
623     memcpy(b, buff, buff_len);
624     t->out.offset += buff_len;
625
626     TRACE("Wrote %zu bytes\n", buff_len);
627
628     return buff_len;
629 }
630
631 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
632 {
633     if (s->current_buffer_idx == -1)
634     {
635         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
636         if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
637         {
638             if (idx == -1)
639             {
640                 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
641                 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
642             }
643             if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
644             {
645                 s->desc->pBuffers[idx].cbBuffer = 0;
646                 s->allow_buffer_resize = TRUE;
647             }
648         }
649         return idx;
650     }
651
652     return -1;
653 }
654
655 static void dump_buffer_desc(SecBufferDesc *desc)
656 {
657     unsigned int i;
658
659     if (!desc) return;
660     TRACE("Buffer desc %p:\n", desc);
661     for (i = 0; i < desc->cBuffers; ++i)
662     {
663         SecBuffer *b = &desc->pBuffers[i];
664         TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
665     }
666 }
667
668 /***********************************************************************
669  *              InitializeSecurityContextW
670  */
671 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
672  PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
673  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
674  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
675  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
676 {
677     struct schan_context *ctx;
678     struct schan_buffers *out_buffers;
679     struct schan_credentials *cred;
680     struct schan_transport transport;
681     int err;
682
683     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
684      debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
685      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
686
687     dump_buffer_desc(pInput);
688     dump_buffer_desc(pOutput);
689
690     if (!phContext)
691     {
692         ULONG_PTR handle;
693
694         if (!phCredential) return SEC_E_INVALID_HANDLE;
695
696         cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
697         if (!cred) return SEC_E_INVALID_HANDLE;
698
699         if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
700         {
701             WARN("Invalid credential use %#x\n", cred->credential_use);
702             return SEC_E_INVALID_HANDLE;
703         }
704
705         ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
706         if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
707
708         handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
709         if (handle == SCHAN_INVALID_HANDLE)
710         {
711             HeapFree(GetProcessHeap(), 0, ctx);
712             return SEC_E_INTERNAL_ERROR;
713         }
714
715         err = pgnutls_init(&ctx->session, GNUTLS_CLIENT);
716         if (err != GNUTLS_E_SUCCESS)
717         {
718             pgnutls_perror(err);
719             schan_free_handle(handle, SCHAN_HANDLE_CTX);
720             HeapFree(GetProcessHeap(), 0, ctx);
721             return SEC_E_INTERNAL_ERROR;
722         }
723
724         /* FIXME: We should be using the information from the credentials here. */
725         FIXME("Using hardcoded \"NORMAL\" priority\n");
726         err = pgnutls_set_default_priority(ctx->session);
727         if (err != GNUTLS_E_SUCCESS)
728         {
729             pgnutls_perror(err);
730             pgnutls_deinit(ctx->session);
731             schan_free_handle(handle, SCHAN_HANDLE_CTX);
732             HeapFree(GetProcessHeap(), 0, ctx);
733         }
734
735         err = pgnutls_credentials_set(ctx->session, GNUTLS_CRD_CERTIFICATE, cred->credentials);
736         if (err != GNUTLS_E_SUCCESS)
737         {
738             pgnutls_perror(err);
739             pgnutls_deinit(ctx->session);
740             schan_free_handle(handle, SCHAN_HANDLE_CTX);
741             HeapFree(GetProcessHeap(), 0, ctx);
742         }
743
744         pgnutls_transport_set_pull_function(ctx->session, schan_pull);
745         pgnutls_transport_set_push_function(ctx->session, schan_push);
746
747         phNewContext->dwLower = handle;
748         phNewContext->dwUpper = 0;
749     }
750     else
751     {
752         ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
753     }
754
755     ctx->req_ctx_attr = fContextReq;
756
757     transport.ctx = ctx;
758     init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
759     init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
760     pgnutls_transport_set_ptr(ctx->session, &transport);
761
762     /* Perform the TLS handshake */
763     err = pgnutls_handshake(ctx->session);
764
765     out_buffers = &transport.out;
766     if (out_buffers->current_buffer_idx != -1)
767     {
768         SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
769         buffer->cbBuffer = out_buffers->offset;
770     }
771
772     *pfContextAttr = 0;
773     if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
774         *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
775
776     switch(err)
777     {
778         case GNUTLS_E_SUCCESS:
779             TRACE("Handshake completed\n");
780             return SEC_E_OK;
781
782         case GNUTLS_E_AGAIN:
783             TRACE("Continue...\n");
784             return SEC_I_CONTINUE_NEEDED;
785
786         case GNUTLS_E_WARNING_ALERT_RECEIVED:
787         case GNUTLS_E_FATAL_ALERT_RECEIVED:
788         {
789             gnutls_alert_description_t alert = pgnutls_alert_get(ctx->session);
790             const char *alert_name = pgnutls_alert_get_name(alert);
791             WARN("ALERT: %d %s\n", alert, alert_name);
792             return SEC_E_INTERNAL_ERROR;
793         }
794
795         default:
796             pgnutls_perror(err);
797             return SEC_E_INTERNAL_ERROR;
798     }
799 }
800
801 /***********************************************************************
802  *              InitializeSecurityContextA
803  */
804 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
805  PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
806  ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
807  PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
808  PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
809 {
810     SECURITY_STATUS ret;
811     SEC_WCHAR *target_name = NULL;
812
813     TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
814      debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
815      Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
816
817     if (pszTargetName)
818     {
819         INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
820         target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
821         MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
822     }
823
824     ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
825             fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
826             phNewContext, pOutput, pfContextAttr, ptsExpiry);
827
828     HeapFree(GetProcessHeap(), 0, target_name);
829
830     return ret;
831 }
832
833 static unsigned int schannel_get_cipher_block_size(gnutls_cipher_algorithm_t cipher)
834 {
835     const struct
836     {
837         gnutls_cipher_algorithm_t cipher;
838         unsigned int block_size;
839     }
840     algorithms[] =
841     {
842         {GNUTLS_CIPHER_3DES_CBC, 8},
843         {GNUTLS_CIPHER_AES_128_CBC, 16},
844         {GNUTLS_CIPHER_AES_256_CBC, 16},
845         {GNUTLS_CIPHER_ARCFOUR_128, 1},
846         {GNUTLS_CIPHER_ARCFOUR_40, 1},
847         {GNUTLS_CIPHER_DES_CBC, 8},
848         {GNUTLS_CIPHER_NULL, 1},
849         {GNUTLS_CIPHER_RC2_40_CBC, 8},
850     };
851     unsigned int i;
852
853     for (i = 0; i < sizeof(algorithms) / sizeof(*algorithms); ++i)
854     {
855         if (algorithms[i].cipher == cipher)
856             return algorithms[i].block_size;
857     }
858
859     FIXME("Unknown cipher %#x, returning 1\n", cipher);
860
861     return 1;
862 }
863
864 static DWORD schannel_get_protocol(gnutls_protocol_t proto)
865 {
866     /* FIXME: currently schannel only implements client connections, but
867      * there's no reason it couldn't be used for servers as well.  The
868      * context doesn't tell us which it is, so assume client for now.
869      */
870     switch (proto)
871     {
872     case GNUTLS_SSL3: return SP_PROT_SSL3_CLIENT;
873     case GNUTLS_TLS1_0: return SP_PROT_TLS1_CLIENT;
874     default:
875         FIXME("unknown protocol %d\n", proto);
876         return 0;
877     }
878 }
879
880 static ALG_ID schannel_get_cipher_algid(gnutls_cipher_algorithm_t cipher)
881 {
882     switch (cipher)
883     {
884     case GNUTLS_CIPHER_UNKNOWN:
885     case GNUTLS_CIPHER_NULL: return 0;
886     case GNUTLS_CIPHER_DES_CBC:
887     case GNUTLS_CIPHER_3DES_CBC: return CALG_DES;
888     case GNUTLS_CIPHER_AES_128_CBC:
889     case GNUTLS_CIPHER_AES_256_CBC: return CALG_AES;
890     case GNUTLS_CIPHER_RC2_40_CBC: return CALG_RC2;
891     default:
892         FIXME("unknown algorithm %d\n", cipher);
893         return 0;
894     }
895 }
896
897 static ALG_ID schannel_get_mac_algid(gnutls_mac_algorithm_t mac)
898 {
899     switch (mac)
900     {
901     case GNUTLS_MAC_UNKNOWN:
902     case GNUTLS_MAC_NULL: return 0;
903     case GNUTLS_MAC_MD5: return CALG_MD5;
904     case GNUTLS_MAC_SHA1:
905     case GNUTLS_MAC_SHA256:
906     case GNUTLS_MAC_SHA384:
907     case GNUTLS_MAC_SHA512: return CALG_SHA;
908     default:
909         FIXME("unknown algorithm %d\n", mac);
910         return 0;
911     }
912 }
913
914 static ALG_ID schannel_get_kx_algid(gnutls_kx_algorithm_t kx)
915 {
916     switch (kx)
917     {
918         case GNUTLS_KX_RSA: return CALG_RSA_KEYX;
919         case GNUTLS_KX_DHE_DSS:
920         case GNUTLS_KX_DHE_RSA: return CALG_DH_EPHEM;
921     default:
922         FIXME("unknown algorithm %d\n", kx);
923         return 0;
924     }
925 }
926
927 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
928         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
929 {
930     struct schan_context *ctx;
931
932     TRACE("context_handle %p, attribute %#x, buffer %p\n",
933             context_handle, attribute, buffer);
934
935     if (!context_handle) return SEC_E_INVALID_HANDLE;
936     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
937
938     switch(attribute)
939     {
940         case SECPKG_ATTR_STREAM_SIZES:
941         {
942             SecPkgContext_StreamSizes *stream_sizes = buffer;
943             gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
944             size_t mac_size = pgnutls_mac_get_key_size(mac);
945             gnutls_cipher_algorithm_t cipher = pgnutls_cipher_get(ctx->session);
946             unsigned int block_size = schannel_get_cipher_block_size(cipher);
947
948             TRACE("Using %zu mac bytes, block size %u\n", mac_size, block_size);
949
950             /* These are defined by the TLS RFC */
951             stream_sizes->cbHeader = 5;
952             stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
953             stream_sizes->cbMaximumMessage = 1 << 14;
954             stream_sizes->cbBuffers = 4;
955             stream_sizes->cbBlockSize = block_size;
956             return SEC_E_OK;
957         }
958         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
959         {
960             unsigned int list_size;
961             const gnutls_datum_t *datum = pgnutls_certificate_get_peers(
962                     ctx->session, &list_size);
963
964             datum = pgnutls_certificate_get_peers(ctx->session, &list_size);
965             if (datum)
966             {
967                 PCCERT_CONTEXT *cert = buffer;
968
969                 *cert = CertCreateCertificateContext(X509_ASN_ENCODING,
970                         datum->data, datum->size);
971                 if (!*cert)
972                     return GetLastError();
973                 else
974                     return SEC_E_OK;
975             }
976             else
977                 return SEC_E_INTERNAL_ERROR;
978         }
979         case SECPKG_ATTR_CONNECTION_INFO:
980         {
981             SecPkgContext_ConnectionInfo *info = buffer;
982             gnutls_protocol_t proto = pgnutls_protocol_get_version(ctx->session);
983             gnutls_cipher_algorithm_t alg = pgnutls_cipher_get(ctx->session);
984             gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
985             gnutls_kx_algorithm_t kx = pgnutls_kx_get(ctx->session);
986
987             info->dwProtocol = schannel_get_protocol(proto);
988             info->aiCipher = schannel_get_cipher_algid(alg);
989             info->dwCipherStrength = pgnutls_cipher_get_key_size(alg);
990             info->aiHash = schannel_get_mac_algid(mac);
991             info->dwHashStrength = pgnutls_mac_get_key_size(mac);
992             info->aiExch = schannel_get_kx_algid(kx);
993             /* FIXME: info->dwExchStrength? */
994             info->dwExchStrength = 0;
995             return SEC_E_OK;
996         }
997
998         default:
999             FIXME("Unhandled attribute %#x\n", attribute);
1000             return SEC_E_UNSUPPORTED_FUNCTION;
1001     }
1002 }
1003
1004 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1005         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1006 {
1007     TRACE("context_handle %p, attribute %#x, buffer %p\n",
1008             context_handle, attribute, buffer);
1009
1010     switch(attribute)
1011     {
1012         case SECPKG_ATTR_STREAM_SIZES:
1013             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1014         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1015             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1016         case SECPKG_ATTR_CONNECTION_INFO:
1017             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1018
1019         default:
1020             FIXME("Unhandled attribute %#x\n", attribute);
1021             return SEC_E_UNSUPPORTED_FUNCTION;
1022     }
1023 }
1024
1025 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1026 {
1027     SecBuffer *b;
1028
1029     if (s->current_buffer_idx == -1)
1030         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1031
1032     b = &s->desc->pBuffers[s->current_buffer_idx];
1033
1034     if (b->BufferType == SECBUFFER_STREAM_HEADER)
1035         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1036
1037     if (b->BufferType == SECBUFFER_DATA)
1038         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1039
1040     return -1;
1041 }
1042
1043 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1044 {
1045     SecBuffer *b;
1046
1047     if (s->current_buffer_idx == -1)
1048         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1049
1050     b = &s->desc->pBuffers[s->current_buffer_idx];
1051
1052     if (b->BufferType == SECBUFFER_TOKEN)
1053     {
1054         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1055         if (idx != s->current_buffer_idx) return -1;
1056         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1057     }
1058
1059     if (b->BufferType == SECBUFFER_DATA)
1060     {
1061         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1062         if (idx != -1)
1063             idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1064         return idx;
1065     }
1066
1067     return -1;
1068 }
1069
1070 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1071         ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1072 {
1073     struct schan_transport transport;
1074     struct schan_context *ctx;
1075     struct schan_buffers *b;
1076     SecBuffer *buffer;
1077     SIZE_T data_size;
1078     char *data;
1079     ssize_t sent = 0;
1080     ssize_t ret;
1081     int idx;
1082
1083     TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1084             context_handle, quality, message, message_seq_no);
1085
1086     if (!context_handle) return SEC_E_INVALID_HANDLE;
1087     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1088
1089     dump_buffer_desc(message);
1090
1091     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1092     if (idx == -1)
1093     {
1094         WARN("No data buffer passed\n");
1095         return SEC_E_INTERNAL_ERROR;
1096     }
1097     buffer = &message->pBuffers[idx];
1098
1099     data_size = buffer->cbBuffer;
1100     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1101     memcpy(data, buffer->pvBuffer, data_size);
1102
1103     transport.ctx = ctx;
1104     init_schan_buffers(&transport.in, NULL, NULL);
1105     if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1106         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
1107     else
1108         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
1109     pgnutls_transport_set_ptr(ctx->session, &transport);
1110
1111     while (sent < data_size)
1112     {
1113         ret = pgnutls_record_send(ctx->session, data + sent, data_size - sent);
1114         if (ret < 0)
1115         {
1116             if (ret != GNUTLS_E_AGAIN)
1117             {
1118                 pgnutls_perror(ret);
1119                 HeapFree(GetProcessHeap(), 0, data);
1120                 ERR("Returning SEC_E_INTERNAL_ERROR\n");
1121                 return SEC_E_INTERNAL_ERROR;
1122             }
1123             else break;
1124         }
1125         sent += ret;
1126     }
1127
1128     TRACE("Sent %zd bytes\n", sent);
1129
1130     b = &transport.out;
1131     b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1132     HeapFree(GetProcessHeap(), 0, data);
1133
1134     return SEC_E_OK;
1135 }
1136
1137 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1138 {
1139     if (s->current_buffer_idx == -1)
1140         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1141
1142     return -1;
1143 }
1144
1145 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1146         PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1147 {
1148     struct schan_transport transport;
1149     struct schan_context *ctx;
1150     SecBuffer *buffer;
1151     SIZE_T data_size;
1152     char *data;
1153     ssize_t received = 0;
1154     ssize_t ret;
1155     int idx;
1156
1157     TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1158             context_handle, message, message_seq_no, quality);
1159
1160     if (!context_handle) return SEC_E_INVALID_HANDLE;
1161     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1162
1163     dump_buffer_desc(message);
1164
1165     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1166     if (idx == -1)
1167     {
1168         WARN("No data buffer passed\n");
1169         return SEC_E_INTERNAL_ERROR;
1170     }
1171     buffer = &message->pBuffers[idx];
1172
1173     data_size = buffer->cbBuffer;
1174     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1175
1176     transport.ctx = ctx;
1177     init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1178     init_schan_buffers(&transport.out, NULL, NULL);
1179     pgnutls_transport_set_ptr(ctx->session, (gnutls_transport_ptr_t)&transport);
1180
1181     while (received < data_size)
1182     {
1183         ret = pgnutls_record_recv(ctx->session, data + received, data_size - received);
1184         if (ret < 0)
1185         {
1186             if (ret == GNUTLS_E_AGAIN)
1187             {
1188                 if (!received)
1189                 {
1190                     pgnutls_perror(ret);
1191                     HeapFree(GetProcessHeap(), 0, data);
1192                     TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1193                     return SEC_E_INCOMPLETE_MESSAGE;
1194                 }
1195                 break;
1196             }
1197             else
1198             {
1199                 pgnutls_perror(ret);
1200                 HeapFree(GetProcessHeap(), 0, data);
1201                 ERR("Returning SEC_E_INTERNAL_ERROR\n");
1202                 return SEC_E_INTERNAL_ERROR;
1203             }
1204         }
1205         received += ret;
1206     }
1207
1208     TRACE("Received %zd bytes\n", received);
1209
1210     memcpy(buffer->pvBuffer, data, received);
1211     buffer->cbBuffer = received;
1212     HeapFree(GetProcessHeap(), 0, data);
1213
1214     return SEC_E_OK;
1215 }
1216
1217 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1218 {
1219     struct schan_context *ctx;
1220
1221     TRACE("context_handle %p\n", context_handle);
1222
1223     if (!context_handle) return SEC_E_INVALID_HANDLE;
1224
1225     ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1226     if (!ctx) return SEC_E_INVALID_HANDLE;
1227
1228     pgnutls_deinit(ctx->session);
1229     HeapFree(GetProcessHeap(), 0, ctx);
1230
1231     return SEC_E_OK;
1232 }
1233
1234 static void schan_gnutls_log(int level, const char *msg)
1235 {
1236     TRACE("<%d> %s", level, msg);
1237 }
1238
1239 static const SecurityFunctionTableA schanTableA = {
1240     1,
1241     NULL, /* EnumerateSecurityPackagesA */
1242     schan_QueryCredentialsAttributesA,
1243     schan_AcquireCredentialsHandleA,
1244     schan_FreeCredentialsHandle,
1245     NULL, /* Reserved2 */
1246     schan_InitializeSecurityContextA, 
1247     NULL, /* AcceptSecurityContext */
1248     NULL, /* CompleteAuthToken */
1249     schan_DeleteSecurityContext,
1250     NULL, /* ApplyControlToken */
1251     schan_QueryContextAttributesA,
1252     NULL, /* ImpersonateSecurityContext */
1253     NULL, /* RevertSecurityContext */
1254     NULL, /* MakeSignature */
1255     NULL, /* VerifySignature */
1256     FreeContextBuffer,
1257     NULL, /* QuerySecurityPackageInfoA */
1258     NULL, /* Reserved3 */
1259     NULL, /* Reserved4 */
1260     NULL, /* ExportSecurityContext */
1261     NULL, /* ImportSecurityContextA */
1262     NULL, /* AddCredentialsA */
1263     NULL, /* Reserved8 */
1264     NULL, /* QuerySecurityContextToken */
1265     schan_EncryptMessage,
1266     schan_DecryptMessage,
1267     NULL, /* SetContextAttributesA */
1268 };
1269
1270 static const SecurityFunctionTableW schanTableW = {
1271     1,
1272     NULL, /* EnumerateSecurityPackagesW */
1273     schan_QueryCredentialsAttributesW,
1274     schan_AcquireCredentialsHandleW,
1275     schan_FreeCredentialsHandle,
1276     NULL, /* Reserved2 */
1277     schan_InitializeSecurityContextW, 
1278     NULL, /* AcceptSecurityContext */
1279     NULL, /* CompleteAuthToken */
1280     schan_DeleteSecurityContext,
1281     NULL, /* ApplyControlToken */
1282     schan_QueryContextAttributesW,
1283     NULL, /* ImpersonateSecurityContext */
1284     NULL, /* RevertSecurityContext */
1285     NULL, /* MakeSignature */
1286     NULL, /* VerifySignature */
1287     FreeContextBuffer,
1288     NULL, /* QuerySecurityPackageInfoW */
1289     NULL, /* Reserved3 */
1290     NULL, /* Reserved4 */
1291     NULL, /* ExportSecurityContext */
1292     NULL, /* ImportSecurityContextW */
1293     NULL, /* AddCredentialsW */
1294     NULL, /* Reserved8 */
1295     NULL, /* QuerySecurityContextToken */
1296     schan_EncryptMessage,
1297     schan_DecryptMessage,
1298     NULL, /* SetContextAttributesW */
1299 };
1300
1301 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1302  'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1303 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1304
1305 void SECUR32_initSchannelSP(void)
1306 {
1307     /* This is what Windows reports.  This shouldn't break any applications
1308      * even though the functions are missing, because the wrapper will
1309      * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1310      */
1311     static const long caps =
1312         SECPKG_FLAG_INTEGRITY |
1313         SECPKG_FLAG_PRIVACY |
1314         SECPKG_FLAG_CONNECTION |
1315         SECPKG_FLAG_MULTI_REQUIRED |
1316         SECPKG_FLAG_EXTENDED_ERROR |
1317         SECPKG_FLAG_IMPERSONATION |
1318         SECPKG_FLAG_ACCEPT_WIN32_NAME |
1319         SECPKG_FLAG_STREAM;
1320     static const short version = 1;
1321     static const long maxToken = 16384;
1322     SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1323               *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1324     const SecPkgInfoW info[] = {
1325         { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1326         { caps, version, UNISP_RPC_ID, maxToken, schannel,
1327             (SEC_WCHAR *)schannelComment },
1328     };
1329     SecureProvider *provider;
1330     int ret;
1331
1332     libgnutls_handle = wine_dlopen(SONAME_LIBGNUTLS, RTLD_NOW, NULL, 0);
1333     if (!libgnutls_handle)
1334     {
1335         WARN("Failed to load libgnutls.\n");
1336         return;
1337     }
1338
1339 #define LOAD_FUNCPTR(f) \
1340     if (!(p##f = wine_dlsym(libgnutls_handle, #f, NULL, 0))) \
1341     { \
1342         ERR("Failed to load %s\n", #f); \
1343         goto fail; \
1344     }
1345
1346     LOAD_FUNCPTR(gnutls_alert_get)
1347     LOAD_FUNCPTR(gnutls_alert_get_name)
1348     LOAD_FUNCPTR(gnutls_certificate_allocate_credentials)
1349     LOAD_FUNCPTR(gnutls_certificate_free_credentials)
1350     LOAD_FUNCPTR(gnutls_certificate_get_peers)
1351     LOAD_FUNCPTR(gnutls_cipher_get)
1352     LOAD_FUNCPTR(gnutls_cipher_get_key_size)
1353     LOAD_FUNCPTR(gnutls_credentials_set)
1354     LOAD_FUNCPTR(gnutls_deinit)
1355     LOAD_FUNCPTR(gnutls_global_deinit)
1356     LOAD_FUNCPTR(gnutls_global_init)
1357     LOAD_FUNCPTR(gnutls_global_set_log_function)
1358     LOAD_FUNCPTR(gnutls_global_set_log_level)
1359     LOAD_FUNCPTR(gnutls_handshake)
1360     LOAD_FUNCPTR(gnutls_init)
1361     LOAD_FUNCPTR(gnutls_kx_get)
1362     LOAD_FUNCPTR(gnutls_mac_get)
1363     LOAD_FUNCPTR(gnutls_mac_get_key_size)
1364     LOAD_FUNCPTR(gnutls_perror)
1365     LOAD_FUNCPTR(gnutls_protocol_get_version)
1366     LOAD_FUNCPTR(gnutls_set_default_priority)
1367     LOAD_FUNCPTR(gnutls_record_recv);
1368     LOAD_FUNCPTR(gnutls_record_send);
1369     LOAD_FUNCPTR(gnutls_transport_set_errno)
1370     LOAD_FUNCPTR(gnutls_transport_set_ptr)
1371     LOAD_FUNCPTR(gnutls_transport_set_pull_function)
1372     LOAD_FUNCPTR(gnutls_transport_set_push_function)
1373 #undef LOAD_FUNCPTR
1374
1375     ret = pgnutls_global_init();
1376     if (ret != GNUTLS_E_SUCCESS)
1377     {
1378         pgnutls_perror(ret);
1379         goto fail;
1380     }
1381
1382     if (TRACE_ON(secur32))
1383     {
1384         pgnutls_global_set_log_level(4);
1385         pgnutls_global_set_log_function(schan_gnutls_log);
1386     }
1387
1388     schan_handle_table = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 64 * sizeof(*schan_handle_table));
1389     if (!schan_handle_table)
1390     {
1391         ERR("Failed to allocate schannel handle table.\n");
1392         goto fail;
1393     }
1394     schan_handle_table_size = 64;
1395
1396     provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1397     if (!provider)
1398     {
1399         ERR("Failed to add schannel provider.\n");
1400         goto fail;
1401     }
1402
1403     SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1404
1405     return;
1406
1407 fail:
1408     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1409     schan_handle_table = NULL;
1410     wine_dlclose(libgnutls_handle, NULL, 0);
1411     libgnutls_handle = NULL;
1412     return;
1413 }
1414
1415 void SECUR32_deinitSchannelSP(void)
1416 {
1417     if (!libgnutls_handle) return;
1418
1419     pgnutls_global_deinit();
1420     wine_dlclose(libgnutls_handle, NULL, 0);
1421 }
1422
1423 #else /* SONAME_LIBGNUTLS */
1424
1425 void SECUR32_initSchannelSP(void) {}
1426 void SECUR32_deinitSchannelSP(void) {}
1427
1428 #endif /* SONAME_LIBGNUTLS */