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