shlwapi: More trace for menu related helpers.
[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_ARCFOUR_40:
887     case GNUTLS_CIPHER_ARCFOUR_128: return CALG_RC4;
888     case GNUTLS_CIPHER_DES_CBC:
889     case GNUTLS_CIPHER_3DES_CBC: return CALG_DES;
890     case GNUTLS_CIPHER_AES_128_CBC:
891     case GNUTLS_CIPHER_AES_256_CBC: return CALG_AES;
892     case GNUTLS_CIPHER_RC2_40_CBC: return CALG_RC2;
893     default:
894         FIXME("unknown algorithm %d\n", cipher);
895         return 0;
896     }
897 }
898
899 static ALG_ID schannel_get_mac_algid(gnutls_mac_algorithm_t mac)
900 {
901     switch (mac)
902     {
903     case GNUTLS_MAC_UNKNOWN:
904     case GNUTLS_MAC_NULL: return 0;
905     case GNUTLS_MAC_MD5: return CALG_MD5;
906     case GNUTLS_MAC_SHA1:
907     case GNUTLS_MAC_SHA256:
908     case GNUTLS_MAC_SHA384:
909     case GNUTLS_MAC_SHA512: return CALG_SHA;
910     default:
911         FIXME("unknown algorithm %d\n", mac);
912         return 0;
913     }
914 }
915
916 static ALG_ID schannel_get_kx_algid(gnutls_kx_algorithm_t kx)
917 {
918     switch (kx)
919     {
920         case GNUTLS_KX_RSA: return CALG_RSA_KEYX;
921         case GNUTLS_KX_DHE_DSS:
922         case GNUTLS_KX_DHE_RSA: return CALG_DH_EPHEM;
923     default:
924         FIXME("unknown algorithm %d\n", kx);
925         return 0;
926     }
927 }
928
929 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
930         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
931 {
932     struct schan_context *ctx;
933
934     TRACE("context_handle %p, attribute %#x, buffer %p\n",
935             context_handle, attribute, buffer);
936
937     if (!context_handle) return SEC_E_INVALID_HANDLE;
938     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
939
940     switch(attribute)
941     {
942         case SECPKG_ATTR_STREAM_SIZES:
943         {
944             SecPkgContext_StreamSizes *stream_sizes = buffer;
945             gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
946             size_t mac_size = pgnutls_mac_get_key_size(mac);
947             gnutls_cipher_algorithm_t cipher = pgnutls_cipher_get(ctx->session);
948             unsigned int block_size = schannel_get_cipher_block_size(cipher);
949
950             TRACE("Using %zu mac bytes, block size %u\n", mac_size, block_size);
951
952             /* These are defined by the TLS RFC */
953             stream_sizes->cbHeader = 5;
954             stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
955             stream_sizes->cbMaximumMessage = 1 << 14;
956             stream_sizes->cbBuffers = 4;
957             stream_sizes->cbBlockSize = block_size;
958             return SEC_E_OK;
959         }
960         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
961         {
962             unsigned int list_size;
963             const gnutls_datum_t *datum;
964
965             datum = pgnutls_certificate_get_peers(ctx->session, &list_size);
966             if (datum)
967             {
968                 PCCERT_CONTEXT *cert = buffer;
969
970                 *cert = CertCreateCertificateContext(X509_ASN_ENCODING,
971                         datum->data, datum->size);
972                 if (!*cert)
973                     return GetLastError();
974                 else
975                     return SEC_E_OK;
976             }
977             else
978                 return SEC_E_INTERNAL_ERROR;
979         }
980         case SECPKG_ATTR_CONNECTION_INFO:
981         {
982             SecPkgContext_ConnectionInfo *info = buffer;
983             gnutls_protocol_t proto = pgnutls_protocol_get_version(ctx->session);
984             gnutls_cipher_algorithm_t alg = pgnutls_cipher_get(ctx->session);
985             gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
986             gnutls_kx_algorithm_t kx = pgnutls_kx_get(ctx->session);
987
988             info->dwProtocol = schannel_get_protocol(proto);
989             info->aiCipher = schannel_get_cipher_algid(alg);
990             info->dwCipherStrength = pgnutls_cipher_get_key_size(alg);
991             info->aiHash = schannel_get_mac_algid(mac);
992             info->dwHashStrength = pgnutls_mac_get_key_size(mac);
993             info->aiExch = schannel_get_kx_algid(kx);
994             /* FIXME: info->dwExchStrength? */
995             info->dwExchStrength = 0;
996             return SEC_E_OK;
997         }
998
999         default:
1000             FIXME("Unhandled attribute %#x\n", attribute);
1001             return SEC_E_UNSUPPORTED_FUNCTION;
1002     }
1003 }
1004
1005 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1006         PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1007 {
1008     TRACE("context_handle %p, attribute %#x, buffer %p\n",
1009             context_handle, attribute, buffer);
1010
1011     switch(attribute)
1012     {
1013         case SECPKG_ATTR_STREAM_SIZES:
1014             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1015         case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1016             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1017         case SECPKG_ATTR_CONNECTION_INFO:
1018             return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1019
1020         default:
1021             FIXME("Unhandled attribute %#x\n", attribute);
1022             return SEC_E_UNSUPPORTED_FUNCTION;
1023     }
1024 }
1025
1026 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1027 {
1028     SecBuffer *b;
1029
1030     if (s->current_buffer_idx == -1)
1031         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1032
1033     b = &s->desc->pBuffers[s->current_buffer_idx];
1034
1035     if (b->BufferType == SECBUFFER_STREAM_HEADER)
1036         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1037
1038     if (b->BufferType == SECBUFFER_DATA)
1039         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1040
1041     return -1;
1042 }
1043
1044 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1045 {
1046     SecBuffer *b;
1047
1048     if (s->current_buffer_idx == -1)
1049         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1050
1051     b = &s->desc->pBuffers[s->current_buffer_idx];
1052
1053     if (b->BufferType == SECBUFFER_TOKEN)
1054     {
1055         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1056         if (idx != s->current_buffer_idx) return -1;
1057         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1058     }
1059
1060     if (b->BufferType == SECBUFFER_DATA)
1061     {
1062         int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1063         if (idx != -1)
1064             idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1065         return idx;
1066     }
1067
1068     return -1;
1069 }
1070
1071 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1072         ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1073 {
1074     struct schan_transport transport;
1075     struct schan_context *ctx;
1076     struct schan_buffers *b;
1077     SecBuffer *buffer;
1078     SIZE_T data_size;
1079     char *data;
1080     ssize_t sent = 0;
1081     ssize_t ret;
1082     int idx;
1083
1084     TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1085             context_handle, quality, message, message_seq_no);
1086
1087     if (!context_handle) return SEC_E_INVALID_HANDLE;
1088     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1089
1090     dump_buffer_desc(message);
1091
1092     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1093     if (idx == -1)
1094     {
1095         WARN("No data buffer passed\n");
1096         return SEC_E_INTERNAL_ERROR;
1097     }
1098     buffer = &message->pBuffers[idx];
1099
1100     data_size = buffer->cbBuffer;
1101     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1102     memcpy(data, buffer->pvBuffer, data_size);
1103
1104     transport.ctx = ctx;
1105     init_schan_buffers(&transport.in, NULL, NULL);
1106     if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1107         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
1108     else
1109         init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
1110     pgnutls_transport_set_ptr(ctx->session, &transport);
1111
1112     while (sent < data_size)
1113     {
1114         ret = pgnutls_record_send(ctx->session, data + sent, data_size - sent);
1115         if (ret < 0)
1116         {
1117             if (ret != GNUTLS_E_AGAIN)
1118             {
1119                 pgnutls_perror(ret);
1120                 HeapFree(GetProcessHeap(), 0, data);
1121                 ERR("Returning SEC_E_INTERNAL_ERROR\n");
1122                 return SEC_E_INTERNAL_ERROR;
1123             }
1124             else break;
1125         }
1126         sent += ret;
1127     }
1128
1129     TRACE("Sent %zd bytes\n", sent);
1130
1131     b = &transport.out;
1132     b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1133     HeapFree(GetProcessHeap(), 0, data);
1134
1135     return SEC_E_OK;
1136 }
1137
1138 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1139 {
1140     if (s->current_buffer_idx == -1)
1141         return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1142
1143     return -1;
1144 }
1145
1146 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1147         PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1148 {
1149     struct schan_transport transport;
1150     struct schan_context *ctx;
1151     SecBuffer *buffer;
1152     SIZE_T data_size;
1153     char *data;
1154     ssize_t received = 0;
1155     ssize_t ret;
1156     int idx;
1157
1158     TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1159             context_handle, message, message_seq_no, quality);
1160
1161     if (!context_handle) return SEC_E_INVALID_HANDLE;
1162     ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1163
1164     dump_buffer_desc(message);
1165
1166     idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1167     if (idx == -1)
1168     {
1169         WARN("No data buffer passed\n");
1170         return SEC_E_INTERNAL_ERROR;
1171     }
1172     buffer = &message->pBuffers[idx];
1173
1174     data_size = buffer->cbBuffer;
1175     data = HeapAlloc(GetProcessHeap(), 0, data_size);
1176
1177     transport.ctx = ctx;
1178     init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1179     init_schan_buffers(&transport.out, NULL, NULL);
1180     pgnutls_transport_set_ptr(ctx->session, (gnutls_transport_ptr_t)&transport);
1181
1182     while (received < data_size)
1183     {
1184         ret = pgnutls_record_recv(ctx->session, data + received, data_size - received);
1185         if (ret < 0)
1186         {
1187             if (ret == GNUTLS_E_AGAIN)
1188             {
1189                 if (!received)
1190                 {
1191                     pgnutls_perror(ret);
1192                     HeapFree(GetProcessHeap(), 0, data);
1193                     TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1194                     return SEC_E_INCOMPLETE_MESSAGE;
1195                 }
1196                 break;
1197             }
1198             else
1199             {
1200                 pgnutls_perror(ret);
1201                 HeapFree(GetProcessHeap(), 0, data);
1202                 ERR("Returning SEC_E_INTERNAL_ERROR\n");
1203                 return SEC_E_INTERNAL_ERROR;
1204             }
1205         }
1206         else if (!ret)
1207             break;
1208
1209         received += ret;
1210     }
1211
1212     TRACE("Received %zd bytes\n", received);
1213
1214     memcpy(buffer->pvBuffer, data, received);
1215     buffer->cbBuffer = received;
1216     HeapFree(GetProcessHeap(), 0, data);
1217
1218     return SEC_E_OK;
1219 }
1220
1221 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1222 {
1223     struct schan_context *ctx;
1224
1225     TRACE("context_handle %p\n", context_handle);
1226
1227     if (!context_handle) return SEC_E_INVALID_HANDLE;
1228
1229     ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1230     if (!ctx) return SEC_E_INVALID_HANDLE;
1231
1232     pgnutls_deinit(ctx->session);
1233     HeapFree(GetProcessHeap(), 0, ctx);
1234
1235     return SEC_E_OK;
1236 }
1237
1238 static void schan_gnutls_log(int level, const char *msg)
1239 {
1240     TRACE("<%d> %s", level, msg);
1241 }
1242
1243 static const SecurityFunctionTableA schanTableA = {
1244     1,
1245     NULL, /* EnumerateSecurityPackagesA */
1246     schan_QueryCredentialsAttributesA,
1247     schan_AcquireCredentialsHandleA,
1248     schan_FreeCredentialsHandle,
1249     NULL, /* Reserved2 */
1250     schan_InitializeSecurityContextA, 
1251     NULL, /* AcceptSecurityContext */
1252     NULL, /* CompleteAuthToken */
1253     schan_DeleteSecurityContext,
1254     NULL, /* ApplyControlToken */
1255     schan_QueryContextAttributesA,
1256     NULL, /* ImpersonateSecurityContext */
1257     NULL, /* RevertSecurityContext */
1258     NULL, /* MakeSignature */
1259     NULL, /* VerifySignature */
1260     FreeContextBuffer,
1261     NULL, /* QuerySecurityPackageInfoA */
1262     NULL, /* Reserved3 */
1263     NULL, /* Reserved4 */
1264     NULL, /* ExportSecurityContext */
1265     NULL, /* ImportSecurityContextA */
1266     NULL, /* AddCredentialsA */
1267     NULL, /* Reserved8 */
1268     NULL, /* QuerySecurityContextToken */
1269     schan_EncryptMessage,
1270     schan_DecryptMessage,
1271     NULL, /* SetContextAttributesA */
1272 };
1273
1274 static const SecurityFunctionTableW schanTableW = {
1275     1,
1276     NULL, /* EnumerateSecurityPackagesW */
1277     schan_QueryCredentialsAttributesW,
1278     schan_AcquireCredentialsHandleW,
1279     schan_FreeCredentialsHandle,
1280     NULL, /* Reserved2 */
1281     schan_InitializeSecurityContextW, 
1282     NULL, /* AcceptSecurityContext */
1283     NULL, /* CompleteAuthToken */
1284     schan_DeleteSecurityContext,
1285     NULL, /* ApplyControlToken */
1286     schan_QueryContextAttributesW,
1287     NULL, /* ImpersonateSecurityContext */
1288     NULL, /* RevertSecurityContext */
1289     NULL, /* MakeSignature */
1290     NULL, /* VerifySignature */
1291     FreeContextBuffer,
1292     NULL, /* QuerySecurityPackageInfoW */
1293     NULL, /* Reserved3 */
1294     NULL, /* Reserved4 */
1295     NULL, /* ExportSecurityContext */
1296     NULL, /* ImportSecurityContextW */
1297     NULL, /* AddCredentialsW */
1298     NULL, /* Reserved8 */
1299     NULL, /* QuerySecurityContextToken */
1300     schan_EncryptMessage,
1301     schan_DecryptMessage,
1302     NULL, /* SetContextAttributesW */
1303 };
1304
1305 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1306  'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1307 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1308
1309 void SECUR32_initSchannelSP(void)
1310 {
1311     /* This is what Windows reports.  This shouldn't break any applications
1312      * even though the functions are missing, because the wrapper will
1313      * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1314      */
1315     static const long caps =
1316         SECPKG_FLAG_INTEGRITY |
1317         SECPKG_FLAG_PRIVACY |
1318         SECPKG_FLAG_CONNECTION |
1319         SECPKG_FLAG_MULTI_REQUIRED |
1320         SECPKG_FLAG_EXTENDED_ERROR |
1321         SECPKG_FLAG_IMPERSONATION |
1322         SECPKG_FLAG_ACCEPT_WIN32_NAME |
1323         SECPKG_FLAG_STREAM;
1324     static const short version = 1;
1325     static const long maxToken = 16384;
1326     SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1327               *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1328     const SecPkgInfoW info[] = {
1329         { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1330         { caps, version, UNISP_RPC_ID, maxToken, schannel,
1331             (SEC_WCHAR *)schannelComment },
1332     };
1333     SecureProvider *provider;
1334     int ret;
1335
1336     libgnutls_handle = wine_dlopen(SONAME_LIBGNUTLS, RTLD_NOW, NULL, 0);
1337     if (!libgnutls_handle)
1338     {
1339         WARN("Failed to load libgnutls.\n");
1340         return;
1341     }
1342
1343 #define LOAD_FUNCPTR(f) \
1344     if (!(p##f = wine_dlsym(libgnutls_handle, #f, NULL, 0))) \
1345     { \
1346         ERR("Failed to load %s\n", #f); \
1347         goto fail; \
1348     }
1349
1350     LOAD_FUNCPTR(gnutls_alert_get)
1351     LOAD_FUNCPTR(gnutls_alert_get_name)
1352     LOAD_FUNCPTR(gnutls_certificate_allocate_credentials)
1353     LOAD_FUNCPTR(gnutls_certificate_free_credentials)
1354     LOAD_FUNCPTR(gnutls_certificate_get_peers)
1355     LOAD_FUNCPTR(gnutls_cipher_get)
1356     LOAD_FUNCPTR(gnutls_cipher_get_key_size)
1357     LOAD_FUNCPTR(gnutls_credentials_set)
1358     LOAD_FUNCPTR(gnutls_deinit)
1359     LOAD_FUNCPTR(gnutls_global_deinit)
1360     LOAD_FUNCPTR(gnutls_global_init)
1361     LOAD_FUNCPTR(gnutls_global_set_log_function)
1362     LOAD_FUNCPTR(gnutls_global_set_log_level)
1363     LOAD_FUNCPTR(gnutls_handshake)
1364     LOAD_FUNCPTR(gnutls_init)
1365     LOAD_FUNCPTR(gnutls_kx_get)
1366     LOAD_FUNCPTR(gnutls_mac_get)
1367     LOAD_FUNCPTR(gnutls_mac_get_key_size)
1368     LOAD_FUNCPTR(gnutls_perror)
1369     LOAD_FUNCPTR(gnutls_protocol_get_version)
1370     LOAD_FUNCPTR(gnutls_set_default_priority)
1371     LOAD_FUNCPTR(gnutls_record_recv);
1372     LOAD_FUNCPTR(gnutls_record_send);
1373     LOAD_FUNCPTR(gnutls_transport_set_errno)
1374     LOAD_FUNCPTR(gnutls_transport_set_ptr)
1375     LOAD_FUNCPTR(gnutls_transport_set_pull_function)
1376     LOAD_FUNCPTR(gnutls_transport_set_push_function)
1377 #undef LOAD_FUNCPTR
1378
1379     ret = pgnutls_global_init();
1380     if (ret != GNUTLS_E_SUCCESS)
1381     {
1382         pgnutls_perror(ret);
1383         goto fail;
1384     }
1385
1386     if (TRACE_ON(secur32))
1387     {
1388         pgnutls_global_set_log_level(4);
1389         pgnutls_global_set_log_function(schan_gnutls_log);
1390     }
1391
1392     schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1393     if (!schan_handle_table)
1394     {
1395         ERR("Failed to allocate schannel handle table.\n");
1396         goto fail;
1397     }
1398     schan_handle_table_size = 64;
1399
1400     provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1401     if (!provider)
1402     {
1403         ERR("Failed to add schannel provider.\n");
1404         goto fail;
1405     }
1406
1407     SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1408
1409     return;
1410
1411 fail:
1412     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1413     schan_handle_table = NULL;
1414     wine_dlclose(libgnutls_handle, NULL, 0);
1415     libgnutls_handle = NULL;
1416     return;
1417 }
1418
1419 void SECUR32_deinitSchannelSP(void)
1420 {
1421     SIZE_T i = schan_handle_count;
1422
1423     if (!libgnutls_handle) return;
1424
1425     /* deinitialized sessions first because a pointer to the credentials
1426      * are stored for the session by calling gnutls_credentials_set. */
1427     while (i--)
1428     {
1429         if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1430         {
1431             struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1432             pgnutls_deinit(ctx->session);
1433             HeapFree(GetProcessHeap(), 0, ctx);
1434         }
1435     }
1436     i = schan_handle_count;
1437     while (i--)
1438     {
1439         if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1440         {
1441             struct schan_credentials *cred;
1442             cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1443             pgnutls_certificate_free_credentials(cred->credentials);
1444             HeapFree(GetProcessHeap(), 0, cred);
1445         }
1446     }
1447     HeapFree(GetProcessHeap(), 0, schan_handle_table);
1448     pgnutls_global_deinit();
1449     wine_dlclose(libgnutls_handle, NULL, 0);
1450 }
1451
1452 #else /* SONAME_LIBGNUTLS */
1453
1454 void SECUR32_initSchannelSP(void)
1455 {
1456     ERR("libgnutls not found, SSL connections will fail\n");
1457 }
1458
1459 void SECUR32_deinitSchannelSP(void) {}
1460
1461 #endif /* SONAME_LIBGNUTLS */